WhereHas Laravel 中的关系计数条件是什么

2022-01-08 00:00:00 php laravel laravel-4 eloquent

我很难理解 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.

相关文章