【发布时间】:2021-02-13 19:41:19
【问题描述】:
我正在使用 Laravel 7。 我需要检索所有有许多团队参与的项目。
这是我在控制器方法中写的代码:
public function index()
{
$projects = Project::select('projects.id as id', 'projects.name as name', 'teams.name as team_name')
->leftJoin('tasks', 'projects.id', '=', 'tasks.project_id')
->join('task_user', 'tasks.id', '=', 'task_user.task_id')
->join('users', 'task_user.user_id', '=', 'users.id')
->join('teams', 'users.team_id', '=', 'teams.id')
->orderBy('projects.id')
->distinct()
->get();
foreach ($projects as $key => $value) {
$projects_length = $projects->where('id', $value['id'])->count();
if($projects_length === 1) {
unset($projects[$key]);
}
}
$projects = $projects->values();
return $projects;
}
我以$projects 返回的数据格式如下:
[
{
"id": 2,
"name": "Creating new app with Symfony",
"team_name": "Warriors"
},
{
"id": 2,
"name": "Creating new app with Symfony",
"team_name": "Guardians"
},
{
"id": 3,
"name": "Creating new app with Vue.js",
"team_name": "Warriors"
},
{
"id": 3,
"name": "Creating new app with Vue.js",
"team_name": "Reds"
}
]
您可以想象,使用类似的响应数据格式是很困难的。
我想把team_name的数据封装成一个数组,如下:
[
{
"id": 2,
"name": "Creating new app with Symfony",
"team_name":
[
"Warriors",
"Guardians"
]
},
{
"id": 3,
"name": "Creating new app with Vue.js",
"team_name":
[
"Warriors",
"Reds"
]
}
]
可以帮忙吗?
【问题讨论】:
标签: laravel collections