結合テーブルの名前をカスタマイズするだけでなく、belongsToMany
メソッドに追加の引数を渡すことで、テーブルのキーの列名をカスタマイズすることもできます。第四の引数が、このような、foreign key name of the model that you are joining to
である3番目の引数が、foreign key name of the model on which you are defining the relationship
である:デフォルト
return $this->belongsToMany('App\Role', 'role_user', 'user_id', 'role_id')
->withPivot(['other_foreign_key_id', 'other_attributes']);
、唯一のモデルキーがピボットオブジェクト上に存在することになります。カスタム -
$user = User::find($id);
foreach ($user->roles as $role) {
echo $role->pivot->created_at;
echo $role->pivot->other_attribute;
}
UPDATE:このようpivot
を使用して
あなたのpivot attributes
使用することができます:あなたのピボットテーブルは、余分な属性が含まれている場合withPivot()
法との関係を定義する際に、上記行われるよう、あなたはそれらを指定する必要があります。 Eloquentのピボットモデル
また、次のように独自のカスタムピボットモデルを定義することもできます。
class RoleUserPivot extends Pivot {
// let's use date mutator for a field
protected $dates = ['completed_at'];
}
さて、雄弁グラブにこのピボットモデルをさせるために、我々はまた、User
とRole
両方にnewPivot
メソッドをオーバーライドする必要があります。
// User model
public function newPivot(Model $parent, array $attributes, $table, $exists)
{
if ($parent instanceof Role) {
return new RoleUserPivot($parent, $attributes, $table, $exists);
}
return parent::newPivot($parent, $attributes, $table, $exists);
}
// Role model
public function newPivot(Model $parent, array $attributes, $table, $exists)
{
if ($parent instanceof User) {
return new RoleUserPivot($parent, $attributes, $table, $exists);
}
return parent::newPivot($parent, $attributes, $table, $exists);
}
がCustom Pivot Tables
希望についての詳細を参照してください。これは役に立ちます!
あなたの答えをありがとうが、私は、例えば、結合テーブルのデータ型を指定することができないか、外部キー制約を設定することができないため、生成されたリンクテーブルは必要ありません。 –
また、 'role_user'テーブルのモデルを作成することもできます。結合テーブルのモデルを作成して要件を満たすことができます。 –
とモデルにどのように添付すればよいですか? –