【问题标题】:How to retrieve data with many to many relationship in Laravel resource如何在 Laravel 资源中检索具有多对多关系的数据
【发布时间】:2021-05-18 06:32:17
【问题描述】:

我正在使用 Laravel 7。 我有三个具有多对多关系的表。这些表是userstask_usertasks。 模型有以下关系:

任务.php:

public function users()
{
    return $this->belongsToMany('App\User')
        ->withPivot('user_id', 'task_id')
        ->withTimestamps();
}

TaskUser.php:

public function task()
{
    return $this->belongsTo('App\Task');
}

public function user()
{
    return $this->belongsTo('App\User');
}

用户.php:

public function tasks()
{
    return $this->belongsToMany('App\Task')
        ->withTimestamps();
}

这是我的控制器方法:

public function get_delayed_tasks() {
    $tasks = Task::select('id', 'name', 'description', 'deadline', 'closed_at', 'status_id', 'project_id')
        ->whereRaw('closed_at > deadline')
        ->get();

    return TaskResource::collection($tasks);
}

这是我的资源:

public function toArray($request)
{
    return [
        'id' => $this->id,
        'name' => $this->name,
        'description' => $this->description,
        'deadline' => $this->deadline,
        'closed_at' => $this->deadline,
        'status' => $this->status->name,
        'project' => $this->project->name,
        'devs' => $this->relationLoaded('users') 
            ? $this->users->pluck('users.name')->unique()->all() 
            : [], //problem
    ];
}

不幸的是,在我收到的资源中的键 dev 中,我总是收到 [],即使我应该收到一个名称数组。 如何检索所有使用过该任务的用户?

【问题讨论】:

  • 那么你应该在任务查询中加载用户,Task::with('users')

标签: laravel


【解决方案1】:

您必须加载关系才能在资源中使用它

控制器

public function get_delayed_tasks() {
    $tasks = Task::with(['users']) // <-- load relationship
        ->select('id', 'name', 'description', 'deadline', 'closed_at', 'status_id', 'project_id')
        ->whereRaw('closed_at > deadline')
        ->get();

    return TaskResource::collection($tasks);
}

资源

'devs' => $this->whenLoaded(
    'users',
    $this->users->pluck('name')->unique()->all(),
    []
)

资源的高级修改,如果您决定创建UserResource 以获取更多数据:

'devs' => UserResource::collection($this->whenLoaded('users'))

【讨论】:

  • 如果您在pluck 中删除users.,它会起作用。否则返回null
  • 我的错,当然是的,因为你访问了关系,所以不需要在 name 属性前面加上 users
猜你喜欢
  • 2017-01-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-03-03
  • 2014-08-11
  • 2023-03-12
  • 2021-04-06
  • 1970-01-01
相关资源
最近更新 更多