Laravel雄辩与多个地方一起加入
我有2个模型:
- 项目
- 任务
一个项目具有多个任务,一个任务只有1个项目。一项任务还具有开始的一周,开始年度,结束周和结束年,我想要的是
Select all the projects and join the tasks where task startWeek = $startWeek and startYear = $startYear and endWeek = $endWeek and endYear = $endYear
,我想获得所有项目并加入在这几周和几年之间开始和结束的任务。
我已经尝试了几件事,其中之一是:
$projects = Project::join('tasks', 'tasks.project_id', '=', 'projects.id')
->where('tasks.start_week', '>=', $startWeek)
->where('tasks.start_week', '>=', $startWeek)
->where('tasks.end_week', '<=', $endWeek)
->where('tasks.end_year', '<=', $endYear)
->get();
但是返回,
0 : {
id:1
name:Schmeler
location:Harvey
created_at:2022-04-26T21:47:55.000000Z
updated_at:2022-04-26T21:47:55.000000Z
project_id:3
task_name:O'Hara
start_week:41
start_year:2022
end_week:5
end_year:2023
}
但是我希望任务像
id: 1,
name: Schmeler,
...other items
tasks: {
0: {
task_id: 1,
task_name: Task2,
},
1: {
task_id: 2,
task_name: Task3
}
}
任何帮助一样在数组中:
I have 2 Models:
- Project
- Task
A Project has multiple tasks and a task has only 1 project. a task also has a start week, start year, end week and end year, what i want is
Select all the projects and join the tasks where task startWeek = $startWeek and startYear = $startYear and endWeek = $endWeek and endYear = $endYear
So i want to get all the projects and join the tasks that start and end between these weeks and years.
I already tried a few things, one of them being:
$projects = Project::join('tasks', 'tasks.project_id', '=', 'projects.id')
->where('tasks.start_week', '>=', $startWeek)
->where('tasks.start_week', '>=', $startWeek)
->where('tasks.end_week', '<=', $endWeek)
->where('tasks.end_year', '<=', $endYear)
->get();
but that returns
0 : {
id:1
name:Schmeler
location:Harvey
created_at:2022-04-26T21:47:55.000000Z
updated_at:2022-04-26T21:47:55.000000Z
project_id:3
task_name:O'Hara
start_week:41
start_year:2022
end_week:5
end_year:2023
}
But i want the task to be in an array like
id: 1,
name: Schmeler,
...other items
tasks: {
0: {
task_id: 1,
task_name: Task2,
},
1: {
task_id: 2,
task_name: Task3
}
}
Any help is welcome :D
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
默认情况下,您不应将连接使用,而是使用关系,而是使用关系。
现在,您可以在这些条件下加载任务,以过滤关系,最简单的方法是将它们与()一起使用
和从那里查询EM。
您的数据将处于您想要的结构中,对于API使用情况,您只需返回该项目,它将自动对其进行转换。
对于迭代或更传统的刀片方法,您将能够这样循环。
You should not use joins for this, instead use relationships, as you get the expected structure by default.
Now you can load your tasks with these conditions, to filter relationships, the easiest approach is to include them using
with()
and query em from there.Your data will be in your wanted structure, for API usage you can just return the project and it will automatically transform it.
For iterating or more traditional blade approaches you would be able to loop it like this.