我有 2 個模型:
- 專案
- 任務
一個專案有多個任務,一個任務只有一個專案。一個任務也有開始周、開始年、結束周和結束年,我想要的是
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
}
}
歡迎任何幫助:D
uj5u.com熱心網友回復:
您不應該為此使用連接,而是使用關系,因為默認情況下您會獲得預期的結構。
class Project
{
public function tasks()
{
return $this->hasMany(Task::class);
}
}
現在您可以使用這些條件加載您的任務,以過濾關系,最簡單的方法是使用它們包含它們with()并從那里查詢它們。
Project::with(['tasks' => function ($query) use ($startWeek, $startYear, $endWeek, $endYear) {
$query->where('tasks.start_week', '>=', $startWeek)
->where('tasks.start_week', '>=', $startYear)
->where('tasks.end_week', '<=', $endWeek)
->where('tasks.end_year', '<=', $endYear);
}])->get();
您的資料將采用您想要的結構,對于 API 使用,您只需回傳專案,它會自動轉換它。
{
$projects = Project::with(...)->get();
return $projects;
}
對于迭代或更傳統的刀片方法,您可以像這樣回圈它。
foreach($project->tasks as $task)
{
$task->task_name; // etc.
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/465750.html
上一篇:介面Stream如何擴展具有型別邊界的基本流介面,就像流介面即Stream<T>一樣?
下一篇:在Laravel的地圖函式中轉儲
