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

2021-12-26 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.

相关文章