我很难理解WhereHas的关系计数情况.文档页面上没有关于它的讨论,但API page谈到了它.引用API.

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

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

Example

Resource型号与ResourceCategory有多对多的关系

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

Relationship condition in 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

Relationship condition in 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()

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.

Question

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

推荐答案

通常,whereHas()会判断您的模型是否有at least one个相关的模型.您可以将$count设置为某个更高的值,以将计数增加到N,并仅获取至少具有N个相关模型的模型.

In your case, calling

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

将只返回包含at least 2个相关类别的Resources个.

Laravel相关问答推荐

为什么只删除了最后一个Like,而没有删除选中的?

在Laravel Livewire中,如果一个输入基于另一个唯一的字段是唯一的,如何判断验证?

Laravel 数据未传递到下拉框

如何使用 laravel 更新单个值

如何提取每组 groupBy 查询的唯一值?

无法在 Laravel 项目中安装 @vitejs/plugin-vue

处理程序类中的错误 - Laravel

Laravel:Blade foreach 循环 bootstrap 列

Laravel transformer vs resource

Laravel Request::input 调用未定义的方法

使用 Laravel Socialite 登录 Facebook

用 laravel 表单确认删除?

Laravel Input:all() 忽略禁用的输入

laravel 5 - assets资源 list 中未定义 css 文件?

Laravel - 自定义时间戳列名称

laravel 4 - 如何限制(采取和跳过)Eloquent的 ORM?

Select,where JSON 包含数组

在 vue.js 中使用 Laravel 的Gate/Authorization

在 laravel 中删除排队的作业(job)

将参数传递给过滤器 - Laravel 4