dongsuishou8039 2014-06-24 16:27
浏览 49
已采纳

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

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?

  • 写回答

6条回答 默认 最新

  • doureng1083 2014-06-24 16:59
    关注

    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:

    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;
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(5条)

报告相同问题?

悬赏问题

  • ¥15 运筹学中在线排序的时间在线排序的在线LPT算法
  • ¥30 求一段fortran代码用IVF编译运行的结果
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 lammps拉伸应力应变曲线分析
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥15 请问Lammps做复合材料拉伸模拟,应力应变曲线问题
  • ¥30 python代码,帮调试,帮帮忙吧