php - 如何在与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');
}
如何检索参加会议的每个用户(参与者)?
解决方案
您可以映射用户以获取姓名和姓氏
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
];
}
推荐阅读
- vue.js - Nuxt生产模式加载资源延迟
- arrays - 在数组中查找字符串时出现类型不匹配
- javascript - 从javascript中的单词中删除字母
- cmake - 如何在 CMakeLists.txt 中调用多个 toolchain.cmake 文件
- c++ - 在 COM 中调用 QueryInterface() 是绝对必要的吗?
- python - 使用重复的优先级将 Torch 张量插入 heapq 时出错
- encryption - 如果我将新的 env var 提交到加密的机密文件,并且 var 名称可以从提交消息中识别,那么安全性会降低多少?
- javascript - 如何使用javascript在aframe中创建快速菜单
- typescript - 使用 ts-jest 和 webpack 允许 Jest 识别和解析模块别名需要什么?
- r - 根据列值在数据集中查找行的问题