首页 文章

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

提问于
浏览
9

因此,belongsToMany关系是多对多关系,因此需要数据透视表

示例我们有一个 users 表和一个 roles 表和一个 user_roles 数据透视表 .

数据透视表有两列, user_idfoo_id ... foo_id 引用角色表中的 id .

为此,我们在 user eloquent模型中编写以下内容:

return $this->belongsToMany('Role', 'user_roles', 'user_id', 'foo_id');

现在,这将在 users 表中查找 id 字段,并将其与 user_roles 表中的 user_id 字段连接 .

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

从laravel的文档来看,目前尚不清楚如何做到这一点 . 在 hasManybelongsTo 之类的其他关系中,我们可以指定 local keyforiegn key 但由于某种原因不在此处 .

我希望users表上的 local keybar_id 而不是 id .

我怎样才能做到这一点?

6 回答

  • 0

    更新:从 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
        );
    }
    

    供参考,以前的方法:

    我假设 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;
    }
    
  • 1

    在Laravel 5.5及以上版本中,

    public function categories()
        {
            return $this->belongsToMany(Category::class,'service_categories','service_id','category_id', 'uuid', 'uuid');
        }
    

    从源代码:

    public function belongsToMany($related, $table = null, $foreignPivotKey = null, $relatedPivotKey = null,
                                      $parentKey = null, $relatedKey = null, $relation = null)
        {}
    
  • 6

    这是最近添加的功能 . 我不得不升级到4.1,因为我也在寻找这个 .

    来自API documentation

    public BelongsToMany belongsToMany(string $related, string $table = null, string $foreignKey = null, string $otherKey = null, string $relation = null)
    

    4.1中添加了 $otherKey$relation 参数 . 使用 $foreignKey$otherKey 参数可以指定关系两侧的键 .

  • 0

    最好的方法是设置主键 .

    class Table extends Eloquent {
    
         protected $table = 'table_name';
    
         protected $primaryKey = 'local_key';
    
  • 0

    belongsToMany 允许定义将在数据透视表中存储che键的字段的名称 but 该方法始终将 primary key 值插入到这些字段中 .

    你必须:

    • 在方法 belongsToMany 中定义表和列;

    • 然后使用protected $primaryKey = 'local_key';你可以选择哪个值存储 .

  • 10

    我最近遇到了同样的问题,我需要有一个关联表,使用ID将两个表连接在一起,而不是主键 . 基本上我所做的是创建我的模型的副本,该模型对数据透视表进行建模,并将主键设置为我希望它使用的值 . 我尝试创建一个模型实例,设置主键然后将其传递给关系,但Laravel不尊重我设置的主键(使用上面的 - > setPrimaryKey()方法) .

    制作模型的副本并设置主键感觉有点'hackish'但最终它应该工作,因为Pivot表模型通常非常小我不认为它将来会导致任何问题 .

    很想看到Laravel的下一个版本中提供的第三个关键选项,让您可以更加具体地了解链接 .

相关问题