Laravel belongsToMany 关系在两个表上定义本地键
所以belongsToMany关系是多对多关系,所以需要数据透视表
So the belongsToMany relationship is a many-to-many relationship so a pivot table is required
例如,我们有一个 users
表和一个 roles
表和一个 user_roles
数据透视表.
Example we have a users
table and a roles
table and a user_roles
pivot table.
数据透视表有两列,user_id
,foo_id
... foo_id
指的是id
角色表.
The pivot table has two columns, user_id
, foo_id
... foo_id
referring to the id
in roles table.
为此,我们在 user
eloquent 模型中编写以下代码:
So to do this we write the following in the user
eloquent model:
return $this->belongsToMany('Role', 'user_roles', 'user_id', 'foo_id');
现在这会在 users
表中查找 id
字段并将其与 user_roles
user_id 字段连接起来> 表.
Now this looks for an id
field in users
table and joins it with the user_id
field in the user_roles
table.
问题是我想指定一个不同的字段,而不是 id
以加入 users
表.例如,我在 users 表中有 bar_id
我想用作 local key
以加入 user_id
Issue is I want to specify a different field, other than id
to join on in the users
table. For example I have bar_id
in the users table that I want to use as the local key
to join with user_id
从 laravel 的文档中,不清楚如何做到这一点.在 hasMany
和 belongsTo
等其他关系中,我们可以指定 local key
和 foriegn key
但由于某种原因不在此处.
From laravel's documentation, it is not clear on how to do this. In other relationships like hasMany
and belongsTo
we can specify local key
and foriegn key
but not in here for some reason.
我希望 users 表上的 local key
是 bar_id
而不仅仅是 id
.
I want the local key
on the users table to be bar_id
instead of just id
.
我该怎么做?
推荐答案
更新:从 Laravel 5.5 开始,可以使用泛型关系方法,如下面的@cyberfly 所述:
Update: as of Laravel 5.5 onwards it is possible with generic relation method, as mentioned by @cyberfly below:
public function categories()
{
return $this->belongsToMany(
Category::class,
'service_categories',
'service_id',
'category_id',
'uuid', // new in 5.5
'uuid' // new in 5.5
);
}
<小时>
供参考,以前的方法:
for reference, previous method:
我假设 id
是您的 User
模型上的主键,因此无法使用 Eloquent 方法执行此操作,因为 belongsToMany
使用 $model->getKey()
来获取该密钥.
I assume id
is the primary key on your User
model, so there is no way to do this with Eloquent methods, because belongsToMany
uses $model->getKey()
to get that key.
因此,您需要创建自定义关系扩展 belongsToMany
来满足您的需要.
So you need to create custom relation extending belongsToMany
that will do what you need.
您可以尝试的快速猜测:(未经测试,但肯定不适用于预加载)
A quick guess you could try: (not tested, but won't work with eager loading for sure)
// User model
protected function setPrimaryKey($key)
{
$this->primaryKey = $key;
}
public function roles()
{
$this->setPrimaryKey('desiredUserColumn');
$relation = $this->belongsToMany('Role', 'user_roles', 'user_id', 'foo_id');
$this->setPrimaryKey('id');
return $relation;
}
相关文章