问题描述
所以belongsToMany关系是一个多对多关系,因此需要一个数据透视表。
例如,我们有一个用户表和角色表和 user_roles 数据透视表。
数据透视表有两列: user_id , foo_id ... foo_id 指向角色表中的 id 。
在用户有用模型中编写以下内容:
return $ this-> belongsToMany ('Role','user_roles','user_id','foo_id');
现在查找用户表中的 c $ c> user_roles 表。
问题是我想指定一个不同的字段,除了 id 在 users 表中加入。例如,我在users表中有 bar_id ,我要用作本地键加入 user_id
从laravel的文档中,不清楚如何做到这一点。在 hasMany 和 belongsTo 之类的其他关系中,我们可以指定本地键 foriegn key ,但由于某种原因不在此处。
我想要键在 bar_id 而不是 id 。
我假设 id 是你的 User 模型的主键,所以没有办法用Eloquent方法,因为 belongsToMany 使用 $ model-> getKey()获取该键。
你需要创建自定义关系扩展 belongsToMany ,这将做你需要的。
一个快速猜测你可以尝试: (未测试,但肯定不能正常加载)
//用户模型
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;
}
So the belongsToMany relationship is a many-to-many relationship so a pivot table is required
Example we have a users table and a roles table and a user_roles pivot table.
The pivot table has two columns, user_id, foo_id... foo_id referring to the id in roles table.
So to do this we write the following in the user eloquent model:
return $this->belongsToMany('Role', 'user_roles', 'user_id', 'foo_id');
Now this looks for an id field in users table and joins it with the user_id field in the user_roles table.
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
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.
I want the local key on the users table to be bar_id instead of just id.
How can I do this?
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.
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; }
这篇关于Laravel belongsToMany关系定义两个表上的本地键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!