它似乎像whereHas方法不能很好地工作。Laravel WhereHas與多態關係
$res = Entreprise::whereHas('labels',function ($q)
{
$q->where('hidden','!=',1);
})
->whereHas('labels',function ($q)
{
$q->whereHidden(1);
})
->get();
dd(count($res)); //shows int 2
這裏是標籤的關係:
public function labels()
{
return $this->morphToMany('Label', 'labelable');
}
這裏是數據庫:
id | nom | deleted_at | created_at | updated_at | junior_id | label_type_id | abbreviation | id_siaje | hidden
6 | Environnord | 0000-00-00 | 0000-00-00 00:00:00 | 0000-00-00 00:00:00 | 1 | 4 | EnvNord | 0 | 1
7 | Salon créer | 0000-00-00 | 0000-00-00 00:00:00 | 0000-00-00 00:00:00 | 1 | 4 | Créer | 0 | 1
8 | Salon WebAnalytics | 0000-00-00 | 0000-00-00 00:00:00 | 0000-00-00 00:00:00 | 1 | 4 | Web | 0 | 0
當我這樣做,而不是:
$res = Entreprise::whereHas('labels',function ($q)
{
$q->where('hidden','!=',1);
$q->whereHidden(1);
})->get()
dd(count($res)); //int 0
我得到的預期值。
在我的數據庫中,企業對象沒有超過1個標籤,因此標籤不是隱藏的,所以其中一個條件應該是false。
編輯
這裏是可加標籤表
+----+----------+--------------+----------------+-----------+
| id | label_id | labelable_id | labelable_type | junior_id |
+----+----------+--------------+----------------+-----------+
| 1 | 1 | 925 | Etude | 1 |
| 2 | 2 | 926 | Etude | 1 |
| 3 | 3 | 927 | Etude | 1 |
| 4 | 2 | 927 | Etude | 1 |
| 5 | 1 | 928 | Etude | 1 |
| 6 | 2 | 928 | Etude | 1 |
| 7 | 3 | 929 | Etude | 1 |
| 8 | 2 | 931 | Etude | 1 |
| 9 | 1 | 933 | Etude | 1 |
| 10 | 2 | 934 | Etude | 1 |
| 11 | 4 | 1 | User | 1 |
| 12 | 5 | 2 | User | 1 |
| 13 | 7 | 1 | Entreprise | 1 |
| 14 | 6 | 2 | Entreprise | 1 |
| 15 | 7 | 3 | Entreprise | 1 |
| 16 | 8 | 4 | Entreprise | 1 |
| 17 | 6 | 5 | Entreprise | 1 |
| 18 | 7 | 6 | Entreprise | 1 |
| 19 | 6 | 7 | Entreprise | 1 |
+----+----------+--------------+----------------+-----------+
正如你所看到的,這個問題可能是,他們是兩個實體的1 labelable_id,和2 labelable_id的兩個實體。但是這是一個morphToMany,所以雄辯應該知道用戶的標籤不應該被考慮在內?
當我看看生成的SQL:
select * from `entreprises`
where `entreprises`.`deleted_at` is null
and `entreprises`.`junior_id` = ?
and (select count(*) from `labels`
inner join `labelables` on `labels`.`id` = `labelables`.`label_id`
where `labels`.`deleted_at` is null
and `labels`.`junior_id` = ?
and `labelables`.`labelable_id` = `entreprises`.`id`
and `hidden` != ?
and `hidden` = ?
and `labels`.`deleted_at` is null
and `labels`.`junior_id` = ?) >= ?
它好像labelables.labelable_type
沒有考慮到,這樣可能是問題的根源。
你的問題是什麼? –
是「return $ this-> morphToMany('Label','labelable')/ * - > select(」問題中的錯字或這是真實的代碼? – marcanuy
嘿,我的問題是,由於企業只有一個標籤在我的數據庫中,我不明白爲什麼第一個語法顯示結果,第二個沒有。@marcanuy:這只是一個錯字,我已經編輯了代碼。 – edi9999