Laravel属于在两个表上定义本地键的ToMany关系

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表.

问题是我想指定一个不同的字段,而不是idusers表中加入.例如,我bar_id在users表中有我想用作local key加入的表user_id

从laravel的文档来看,目前尚不清楚如何做到这一点.在其他关系,喜欢hasManybelongsTo我们可以指定local keyforiegn 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)

供参考,以前的方法:

我假设idUser模型的主键,因此无法用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)


cyb*_*fly 6

在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)