dougou5844 2016-07-01 06:15
浏览 247
已采纳

通过Laravel中多对多关系的has-many-through检索远程关系

I have the following models in my application

  • User
  • Group
  • Task

which have the following relationships

  • User and Group have a many-to-many relationship
  • Task and Group have a many-to-many relationship

So basically a user can belong to more than one group and each group can have more than one task.

Following is the table structure.

users

  • id
  • name

groups

  • id
  • name

tasks

  • id
  • name

group_user

  • id
  • group_id (foreign key with groups table)
  • user_id (foreign key with users table)

group_tasks

  • id
  • group_id (foreign key with groups table)
  • task_id (foreign key with tasks table)

Now I want to retrieve all the tasks for the user.

I tried the following approaches and both didn't work.

Approach 1

  • $user->groups() gives the list of groups for a user
  • $group->tasks() gives the list of tasks for a group

So I tried

$user->groups()->tasks() but it didn't work.

Approach 2

I tried Has Many Through by adding this to my User model

public function tasks()
{
    return $this->hasManyThrough(Task::class, Group::class);
}

but even that didn't work. The following is the error that I am getting

QueryException in Connection.php line 713:
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'groups.user_id' in 'field list' (SQL: select `tasks`.*, `groups`.`user_id` from `tasks` inner join `groups` on `groups`.`id` = `tasks`.`group_id` where `groups`.`user_id` = 1)

My guess is that this is happening because it is expecting one-to-many relationship, but I have a many-to-many relationship.

So is there a way to retrieve it without getting all groups and then looping through them?

  • 写回答

2条回答 默认 最新

  • dt614037527 2016-07-01 10:53
    关注
    User Model
    
    public function groups()
    {
        return $this->belongsToMany('App\Group');
    }
    
    Group Model
    
    public function tasks()
    {
        return $this->belongsToMany('App\Task');
    }
    
    Task Model
    
    public function groups()
    {
        return $this->belongsToMany('App\Group');
    }
    

    Retrieving all tasks for a user.

    $user = User::find(1);
    
    $user->load('groups.tasks');
    
    $tasks = $user->groups->pluck('tasks')->collapse();
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 Arcgis相交分析无法绘制一个或多个图形
  • ¥15 seatunnel-web使用SQL组件时候后台报错,无法找到表格
  • ¥15 fpga自动售货机数码管(相关搜索:数字时钟)
  • ¥15 用前端向数据库插入数据,通过debug发现数据能走到后端,但是放行之后就会提示错误
  • ¥30 3天&7天&&15天&销量如何统计同一行
  • ¥30 帮我写一段可以读取LD2450数据并计算距离的Arduino代码
  • ¥15 飞机曲面部件如机翼,壁板等具体的孔位模型
  • ¥15 vs2019中数据导出问题
  • ¥20 云服务Linux系统TCP-MSS值修改?
  • ¥20 关于#单片机#的问题:项目:使用模拟iic与ov2640通讯环境:F407问题:读取的ID号总是0xff,自己调了调发现在读从机数据时,SDA线上并未有信号变化(语言-c语言)