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

What is relationship count condition in WhereHas Laravel(WhereHas Laravel 中的关系计数条件是什么)
本文介绍了WhereHas Laravel 中的关系计数条件是什么的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很难理解 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 中的关系计数条件是什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Convert JSON integers and floats to strings(将JSON整数和浮点数转换为字符串)
in php how do I use preg replace to turn a url into a tinyurl(在php中,如何使用preg替换将URL转换为TinyURL)
all day appointment for ics calendar file wont work(ICS日历文件的全天约会不起作用)
trim function is giving unexpected values php(Trim函数提供了意外的值php)
Basic PDO connection to MySQL(到MySQL的基本PDO连接)
PHP number_format returns 1.00(Php number_Format返回1.00)