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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31624165/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 12:02:19  来源:igfitidea点击:

What is relationship count condition in WhereHas Laravel

phplaravellaravel-4eloquent

提问by hhsadiq

I am having a difficulty understanding the relationship count condition in WhereHas. The docs page does not have discussion about it but API pagetalks about it. Quote from API.

我很难理解WhereHas 中的关系计数条件。文档页面没有讨论它,但API 页面谈论它。来自 API 的报价。

Builder|Builder whereHas(string $relation, Closure $callback, string $operator = '>=', int $count = 1)

Add a relationship count condition to the query with where clauses.

Builder|Builder whereHas(string $relation, Closure $callback, string $operator = '>=', int $count = 1)

使用 where 子句向查询添加关系计数条件。

Example

例子

A ResourceModel has Many to Many relation to ResourceCategory

一个Resource模型具有多对多关系ResourceCategory

public function categories()
{
    return $this->belongsToMany('ResourceCategory', 'resource_category_mapping');
}

Relationship condition in Has

Has中的关系条件

The relationship condition in Hasis working as expected.

Has 中的关系条件按预期工作。

Resource::has('categories', '>', 1)->get()
//this return all resources which have more than one catgories

Relationship condition in WhereHas

WhereHas 中的关系条件

The relationship condition in WhereHas is not working as expected. I am sure I have misunderstood it.

WhereHas 中的关系条件未按预期工作。我确定我误解了它。

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.

上面的代码应该返回类别属于 [1, 2, 4] 之一的资源,并且该资源有多个类别。但事实并非如此。

Question

Kindly explain the relationship condition in WhereHas, may be providing an example would be much helpful.

请解释WhereHas中的关系条件,可能提供一个例子会很有帮助。

回答by jedrzej.kurylo

Normally, whereHas()checks if your model has at least onerelated model. You can set $countto some higher value to increase the count to Nand fetch only the models that have at least Nrelated models.

通常,whereHas() 会检查您的模型是否至少有一个相关模型。您可以将$count设置更高的值以将计数增加到N并仅获取至少具有N 个相关模型的模型。

In your case, calling

在你的情况下,打电话

Resource::has('categories', '>', 2)->get();

will return only those Resourcesthat have at least 2related categories.

将返回只有那些资源具有至少2个相关类别。