gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 07:15:09 24 4
gpt4 key购买 nike

让我在这里展示来自 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com