首页 > 解决方案 > Spatie 查询生成器过滤嵌套关系

问题描述

使用 Spatie Query Builder 我想扩展嵌套关系的过滤器

以下代码使用工作正常的关系作业计数获取位置。我想将工作关系的过滤器扩展为可以查询多对多的关系 job.level。我怎么去?

过滤器看起来像/options/?filter[job.level]=2

德国 - 12, 意大利 - 34

  $locations = QueryBuilder::for(JobLocation::class)
            ->select('id as value', 'title', 'country_id')
            ->orderBy('title')
            ->withCount(['job as counts' => function ($q) {
                $q->whereNull('deleted_at');
            }])
            ->whereHas('country', function ($q) {
                $q->where('id', '=', 80);
            })
            ->allowedAppends(
                'job',
            )
            ->allowedIncludes('job', 'job.level',)
            ->allowedFilters([
                AllowedFilter::exact('job.language_id'),
                AllowedFilter::exact('job.level', 'job.level.id')
            ])->get();

标签: laravelquery-builderlaravel-query-builder

解决方案


我认为您正在寻找 whereHas 功能。请参阅此处查询关系存在的文档。但是你已经在为国家关系这样做了,这没有什么不同。

所以我认为你的看起来像:

  $locations = QueryBuilder::for(JobLocation::class)
        ->select('id as value', 'title', 'country_id')
        ->orderBy('title')
        ->withCount(['job as counts' => function ($q) {
            $q->whereNull('deleted_at');
        }])
        ->whereHas('country', function ($q) {
            $q->where('id', '=', 80);
        })
        //New query constraint here
        ->whereHas('job', function ($q) {
            $q->where('level', '=', 2);
        })
        ->allowedAppends(
            'job',
        )
        ->allowedIncludes('job', 'job.level',)
        ->allowedFilters([
            AllowedFilter::exact('job.language_id'),
            AllowedFilter::exact('job.level', 'job.level.id')
        ])->get();

推荐阅读