問題描述
我很難理解 WhereHas 中的關系計數條件.文檔頁面沒有關于它的討論,但 API 頁面討論了它.來自 API 的報價.
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 子句向查詢添加關系計數條件.
Add a relationship count condition to the query with where clauses.
示例
Resource
模型與 ResourceCategory
public function categories()
{
return $this->belongsToMany('ResourceCategory', 'resource_category_mapping');
}
Has 中的關系條件
Has 中的關系條件按預期工作.
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 中的關系條件
WhereHas 中的關系條件未按預期工作.我確定我誤解了它.
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()
上面的代碼應該返回類別屬于 [1, 2, 4] 之一的資源,并且該資源有多個類別.但事實并非如此.
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.
問題
請解釋WhereHas中的關系條件,可能提供一個例子會很有幫助.
Kindly explain the relationship condition in WhereHas, may be providing an example would be much helpful.
推薦答案
通常,whereHas() 檢查您的模型是否具有至少一個相關模型.您可以將 $count 設置為更高的值,以將計數增加到 N 并僅獲取至少具有 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 個 相關類別的資源.
will return only those Resources that have at least 2 related categories.
這篇關于什么是 WhereHas Laravel 中的關系計數條件的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!