[英]How to query an Eloquent ORM many-to-many relationship
我有在各州(即澳大利亞各州)工作的員工。
員工存儲在用戶表中。 狀態存儲在狀態表中。 兩者之間的多對多關系存儲在staff_state中。
在我的 Staff 模型上,我有一個方法如下:
public function workStates()
{
return $this->belongsToMany(Core\State::class);
}
我想檢索所有在新南威爾士州工作且名字或姓氏包含字母“dan”的用戶。 這是我的雄辯查詢:
$query = Staff::whereHas('workStates', function ($query) {
$query->where('state_id', '=', 'NSW');})
->where('first_name', 'like', '%dan%')
->orWhere('last_name', 'like', '%dan%')
->orderBy('first_name', 'asc')
->orderBy('last_name', 'asc');
我的查詢結果都包含字母“dan”,但是有些工作人員不在新南威爾士州工作。 我究竟做錯了什么?
這是 Eloquent 生成的 SQL 查詢:
select * from `users` where (exists
(select * from `states` inner join `staff_state` on `states`.`id` = `staff_state`.`state_id`
where `users`.`id` = `staff_state`.`staff_id` and `state_id` = 'NSW')
and `first_name` like '%dan%' or `last_name` like '%dan%')
and `users`.`deleted_at` is null order by `first_name` asc, `last_name` asc
謝謝..!
我會嘗試將first_name
和last_name
條件分組。
我認為您可以通過將閉包傳遞給where()
函數來做到這一點。 也許是這樣的:
Staff::whereHas('workStates', function ($query) {
$query->where('state_id', '=', 'NSW');
})->where(function($query) {
$query
->where('first_name', 'like', '%dan%')
->orWhere('last_name', 'like', '%dan%');
})->orderBy('first_name', 'asc')->orderBy('last_name', 'asc');
您不應使用state_id
,而應使用states
表中的真實列名。 此外, where()
閉包中的組名相關邏輯。 例如,如果列名稱是name
:
$state = 'NSW';
$name = 'dan';
Staff::whereHas('workStates', function ($query) use($state) {
$query->where('name', $state);
})
->where(function($query) use($name) {
$query->where('first_name', 'like', '%' . $name . '%')
->orWhere('last_name', 'like', '%' . $name . '%');
})
->orderBy('first_name', 'asc')
->orderBy('last_name', 'asc')
->get();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.