除了自定义连接表的名称外,您还可以通过将附加参数传递给belongsToMany 方法来自定义表上键的列名。第三个参数是foreign key name of the model on which you are defining the relationship,而第四个参数是foreign key name of the model that you are joining to,像这样:
return $this->belongsToMany('App\Role', 'role_user', 'user_id', 'role_id')
->withPivot(['other_foreign_key_id', 'other_attributes']);
默认情况下,只有模型键会出现在数据透视对象上。如果您的数据透视表包含额外的属性,您必须在使用withPivot() 方法定义关系时指定它们,如上所述:
您可以像这样使用pivot attributes 和pivot:
$user = User::find($id);
foreach ($user->roles as $role) {
echo $role->pivot->created_at;
echo $role->pivot->other_attribute;
}
更新 - Eloquent 中的自定义枢轴模型
您还可以像这样定义自己的自定义数据透视模型:
class RoleUserPivot extends Pivot {
// let's use date mutator for a field
protected $dates = ['completed_at'];
}
现在,为了让 Eloquent 抓取这个枢轴模型,我们还需要在 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
希望这会有所帮助!