use*_*811 11 php sql database laravel laravel-4
因此,belongsToMany关系是多对多关系,因此需要数据透视表
例如,我们有一个users
表,一个roles
表和一个user_roles
数据透视表.
枢轴表有两列,user_id
,foo_id
... foo_id
指的是id
在角色表.
为此,我们在user
雄辩的模型中编写以下内容:
return $this->belongsToMany('Role', 'user_roles', 'user_id', 'foo_id');
现在,这个寻找一个id
在外地users
表,并与加入它user_id
在该领域user_roles
表.
问题是我想指定一个不同的字段,而不是id
在users
表中加入.例如,我bar_id
在users表中有我想用作local key
加入的表user_id
从laravel的文档来看,目前尚不清楚如何做到这一点.在其他关系,喜欢hasMany
和belongsTo
我们可以指定local key
和foriegn key
,但不会在这里的某些原因.
我希望local key
用户表上的bar_id
而不仅仅是id
.
我怎样才能做到这一点?
Jar*_*zyk 16
更新:从Laravel 5.5开始,可以使用通用关系方法,如下面的@cyberfly所述:
public function categories()
{
return $this->belongsToMany(
Category::class,
'service_categories',
'service_id',
'category_id',
'uuid', // new in 5.5
'uuid' // new in 5.5
);
}
Run Code Online (Sandbox Code Playgroud)
供参考,以前的方法:
我假设id
是User
模型的主键,因此无法用Eloquent方法执行此操作,因为belongsToMany
用于$model->getKey()
获取该键.
因此,您需要创建自定义关系扩展belongsToMany
,以满足您的需求.
你可以尝试一下快速猜测:(未经过测试,但肯定无法正常加载)
// 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;
}
Run Code Online (Sandbox Code Playgroud)
在Laravel 5.5及以上版本中,
public function categories()
{
return $this->belongsToMany(Category::class,'service_categories','service_id','category_id', 'uuid', 'uuid');
}
Run Code Online (Sandbox Code Playgroud)
从源代码:
public function belongsToMany($related, $table = null, $foreignPivotKey = null, $relatedPivotKey = null,
$parentKey = null, $relatedKey = null, $relation = null)
{}
Run Code Online (Sandbox Code Playgroud)