問題描述
我很難理解 WhereHas 中的關(guān)系計(jì)數(shù)條件.文檔頁面沒有關(guān)于它的討論,但 API 頁面討論了它.來自 API 的報(bào)價(jià).
I am having a difficulty understanding the relationship count condition in WhereHas. The docs page does not have discussion about it but API page talks about it. Quote from API.
Builder|Builder whereHas(string $relation, Closure $callback, string$operator = '>=', int $count = 1)
Builder|Builder whereHas(string $relation, Closure $callback, string $operator = '>=', int $count = 1)
使用 where 子句向查詢添加關(guān)系計(jì)數(shù)條件.
Add a relationship count condition to the query with where clauses.
示例
Resource
模型與 ResourceCategory
public function categories()
{
return $this->belongsToMany('ResourceCategory', 'resource_category_mapping');
}
Has 中的關(guān)系條件
Has 中的關(guān)系條件按預(yù)期工作.
The relationship condition in Has is working as expected.
Resource::has('categories', '>', 1)->get()
//this return all resources which have more than one catgories
WhereHas 中的關(guān)系條件
WhereHas 中的關(guān)系條件未按預(yù)期工作.我確定我誤解了它.
The relationship condition in WhereHas is not working as expected. I am sure I have misunderstood it.
Resource::whereHas('categories', function ( $query){
$query->whereIn('resource_category_id', [1, 2, 4]);
}, '>', 1)->get()
上面的代碼應(yīng)該返回類別屬于 [1, 2, 4] 之一的資源,并且該資源有多個(gè)類別.但事實(shí)并非如此.
The above code should return resources which whose categories belong to either of [1, 2, 4] and the resource has more than one categories. But it is not.
問題
請(qǐng)解釋W(xué)hereHas中的關(guān)系條件,可能提供一個(gè)例子會(huì)很有幫助.
Kindly explain the relationship condition in WhereHas, may be providing an example would be much helpful.
推薦答案
通常,whereHas() 檢查您的模型是否具有至少一個(gè)相關(guān)模型.您可以將 $count 設(shè)置為更高的值,以將計(jì)數(shù)增加到 N 并僅獲取至少具有 N 個(gè)相關(guān)模型的模型.
Normally, whereHas() checks if your model has at least one related model. You can set $count to some higher value to increase the count to Nand fetch only the models that have at least N related models.
在你的情況下,打電話
Resource::has('categories', '>', 2)->get();
將僅返回具有至少 2 個(gè) 相關(guān)類別的資源.
will return only those Resources that have at least 2 related categories.
這篇關(guān)于什么是 WhereHas Laravel 中的關(guān)系計(jì)數(shù)條件的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!