What is relationship count condition in 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 中的关系计数条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:什么是 WhereHas Laravel 中的关系计数条件
基础教程推荐
- PHP 守护进程/worker 环境 2022-01-01
- 如何在 Symfony 和 Doctrine 中实现多对多和一对多? 2022-01-01
- 在 CakePHP 2.0 中使用 Html Helper 时未定义的变量 2021-01-01
- Doctrine 2 - 在多对多关系中记录更改 2022-01-01
- 找不到类“AppHttpControllersDB",我也无法使用新模型 2022-01-01
- 如何在 XAMPP 上启用 mysqli? 2021-01-01
- 使用 PDO 转义列名 2021-01-01
- 在 yii2 中迁移时出现异常“找不到驱动程序" 2022-01-01
- HTTP 与 FTP 上传 2021-01-01
- phpmyadmin 错误“#1062 - 密钥 1 的重复条目‘1’" 2022-01-01