Laravel - 我应该在哪个模型上定义数据透视表?

标签 laravel eloquent pivot-table

让我在这里展示来自 Laravel doc 的场景: 相关的数据库表是usersrolesrole_users。表名是不言自明的。

用户模型:

class User extends Model
{
    /**
     * The roles that belong to the user.
     */
    public function roles()
    {
        return $this->belongsToMany('App\Role');
    }
}

文档继续说:

As mentioned previously, to determine the table name of the relationship's joining table, Eloquent will join the two related model names in alphabetical order. However, you are free to override this convention. You may do so by passing a second argument to the belongsToMany method:

return $this->belongsToMany('App\Role', 'role_user');

然后它定义了关系的逆:

角色模型:

class Role extends Model
{
    /**
     * The users that belong to the role.
     */
    public function users()
    {
        return $this->belongsToMany('App\User');
    }
}

然后它说:

Since we're reusing the belongsToMany method, all of the usual table and key customization options are available when defining the inverse of many-to-many relationships.

目前我的理解:

pivot 表已在 User 模型中定义,文档中说
所有常用的表和键自定义选项都可以在角色模型中使用多对多关系的逆向。

因此似乎也可以选择在 Role 模型中定义数据透视表。

默认情况下,Eloquent 会按照字母顺序连接两个相关的模型名称来定义数据透视表名称。

当数据透视表名称不符合默认约定时,我应该在哪个模型上定义数据透视表?

最佳答案

/**
* On the User model
*/
public function roles()
{
    return  $this->belongsToMany('App\Role', 'role_users', 'user_id', 'role_id')->withTimestamps();
}


/**
* On the roles model
*/
public function users()
{
    return  $this->belongsToMany('App\Role', 'role_users', 'role_id', 'user_id')->withTimestamps();
}

其中 role_users 是数据透视表,第一个参数是 foreignPivotKey 第二个参数是 relatedPivotKey

通过这种方式,您在两个模型上都有一个完整的关系。 您可以访问所有用户角色,反之亦然

关于Laravel - 我应该在哪个模型上定义数据透视表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59681835/

相关文章:

php - 如何将列数据转换为行数据

mysql - 统计MySQL中的空数据

google-sheets - 我可以使用第二个条件订购数据透视表吗?

python - 如何在 Pandas 的数据透视表中搜索数据?

php - 如何更改 laravel 中路由系统使用的基本路径

php - Laravel 关系使用Where

php - 在 Laravel 中使用 IFNULL

php - 从多个记录中获取主键-laravel

laravel - 在 Laravel 4 中发送模型的嵌套数组的最佳方式是什么?

php - 搜索表单的条件