![](/img/trans.png)
[英]Laravel whereHas relation where column can be equal to any in array but no other
[英]Laravel - whereHas with where affect other rows
我有一個應用程序,我想根據子條件獲取父記錄。 當前的問題是我有學生,他們有多個學習領域,而一個研究領域屬於一個系。 數據透視表students_study_fields
具有屬性study_status_id
。
我需要的是,例如,獲取所有屬於“ prf”教師的學生及其學習領域,並且pivot具有study_status_id = 1
。
所以我寫了這樣的查詢。
return Student::with(['studyfields' => function ($query1) use ($studyStatusId, $facultyAbbreviation) {
$query1->whereHas('pivot', function ($query2) use ($studyStatusId, $facultyAbbreviation) {
$query2->where('study_status_id', $studyStatusId);
});
$query1->whereHas('studyprogram', function ($query4) use ($facultyAbbreviation) {
$query4->whereHas('faculty', function ($query5) use ($facultyAbbreviation) {
$query5->where('abbreviation', $facultyAbbreviation);
});
});
}])->get();
但是該查詢也獲取學生study_status_id = 2
,因為存在該記錄域(其代碼)與學生相關的記錄,其中study_status_id = 1
。
因此,我不想在某個位置存在樞軸中status = 1
記錄但僅當當前行的status = 1
才包含此研究區域
您需要鏈接查詢...
return Student::with(['studyfields' => function ($query1) use ($studyStatusId, $facultyAbbreviation) {
$query1->whereHas('pivot', function ($query2) use ($studyStatusId, $facultyAbbreviation) {
$query2->where('study_status_id', $studyStatusId);
})->whereHas('studyprogram', function ($query4) use ($facultyAbbreviation) {
$query4->whereHas('faculty', function ($query5) use ($facultyAbbreviation) {
$query5->where('abbreviation', $facultyAbbreviation);
});
});
}])->get();
否則,它將重新啟動query1,因此您將不會得到AND
類型的查詢,僅會得到第二部分
whereHas
:但是,我想警告您,如果在每個值中有很多行, whereHas
是一個緩慢的查詢。 我個人更喜歡使用簡單的->where
查詢並利用->whereIn
方法來獲取ID。
我為我的情況找到了解決方案
$students = Student::with(['studyfields' => function ($q) use ($studyStatusId) {
$q->whereHas('pivot')->where('study_status_id', $studyStatusId);
}])
->whereHas('studyfields', function ($q) use ($facultyAbbreviation) {
$q->whereHas('studyprogram', function ($q) use ($facultyAbbreviation) {
$q->where('faculty_abbreviation', $facultyAbbreviation);
});
})
->get();
$students = $students->filter(function ($student) {
return count($student->studyfields) > 0;
})->values();
上面的查詢從特定系獲取所有學生,並且如果studyfields數組不包含特定的study_status,請留空數組,以便稍后我可以假設每個學生至少屬於一個學習場,從空數組中過濾集合。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.