我很难理解WhereHas的关系计数情况.文档页面上没有关于它的讨论,但API page谈到了它.引用API.
Builder|Builder whereHas(string $relation, Closure $callback, string $operator = '>=', int $count = 1)
Add a relationship count condition to the query with where clauses.
Example
Resource
型号与ResourceCategory
有多对多的关系
public function categories()
{
return $this->belongsToMany('ResourceCategory', 'resource_category_mapping');
}
Relationship condition in 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
Relationship condition in 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()
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.
Question
Kindly explain the relationship condition in WhereHas, may be providing an example would be much helpful.