【问题标题】:Laravel Eloquent many-to-many relationship: Use explicit pivot tableLaravel Eloquent 多对多关系:使用显式数据透视表
【发布时间】:2016-12-19 14:21:43
【问题描述】:

如何选择显式表(带有迁移和模型)作为数据透视表?

我的模型是

User
-id

Role
-id

user_role
-user_id
-role_id
-other_foreign_key_id
-other_attributes
-...

我知道在 laravel 中一般有多少多对多的关系。但在文档中,他们只使用自动生成的连接表,我无法为其他列定义额外的外键约束或数据类型。

我想要的是我有自己的 user_role 表的迁移和模型,并将其用作枢轴,但我不知道如何将已定义的表显式链接为 m 对 n 关系的枢轴。

提前致谢。

【问题讨论】:

    标签: laravel eloquent many-to-many


    【解决方案1】:

    除了自定义连接表的名称外,您还可以通过将附加参数传递给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 attributespivot

    $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 抓取这个枢轴模型,我们还需要在 UserRole 上覆盖 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表创建模型,您可以通过为连接表创建模型来满足您的要求!
    • 我如何将它附加到模型中?
    • 对不起,我没听明白!
    • 我用迁移和自己的模型制作了连接表。但是我应该在 belongsToMany() 函数中输入什么参数来使用我自己定义的表呢?
    猜你喜欢
    • 2023-02-05
    • 2014-12-07
    • 1970-01-01
    • 1970-01-01
    • 2020-07-28
    • 2018-09-23
    • 2014-12-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多