首页 > 解决方案 > 如何在与laravel的多对多关系中检索特定列的嵌套值

问题描述

我创建了一个资源MeetingResource.php,它应该通过 API 调用返回所有会议数据。

这是该资源的主要功能的代码:

public function toArray($request)
{
    return [
        'id' => $this->id,
        'room_id' => $this->room_id,
        'description' => $this->description,
        'participants' => $this->users[0]['name'] . " " . $this->users[0]['surname'], //here
        'date' => $this->date,
        'start' => $this->start,
        'end' => $this->end,
        'is_active' => $this->is_active
    ];
}

我的元素有问题,participants因为它只返回第一个参与者,但我需要上述格式的每个参与者。

users表和表之间的关系meetings是多对多的。

这是 meeting.php 模型中的关系:

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

这是 user.php 模型中的关系:

public function meetings()
{
    return $this->belongsToMany('App\Meeting');
}

如何检索参加会议的每个用户(参与者)?

标签: phplaravel

解决方案


您可以映射用户以获取姓名和姓氏

public function toArray($request)
{
    return [
        'id' => $this->id,
        'room_id' => $this->room_id,
        'description' => $this->description,
        'participants' => $this->users->map(function($user){
                return $user->name . " " . $user->surname;
            })->values()->all(), //here
        'date' => $this->date,
        'start' => $this->start,
        'end' => $this->end,
        'is_active' => $this->is_active
    ];
}

推荐阅读