【问题标题】:Spatie Query Builder filter nested relationsSpatie 查询生成器过滤嵌套关系
【发布时间】:2021-06-26 11:39:39
【问题描述】:

使用 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();

【问题讨论】:

    标签: laravel query-builder laravel-query-builder


    【解决方案1】:

    我认为您正在寻找 whereHas 函数。请参阅querying relation existence here 的文档。但是你已经在为国家关系这样做了,这没有什么不同。

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

      $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();
    

    【讨论】:

    • 感谢您的反馈!我认为我可以使用内置过滤器方法使用 spatie 查询生成器来管理它,并且不需要从请求的 url 中提取参数。
    猜你喜欢
    • 2018-08-04
    • 2018-11-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-07
    • 2020-11-22
    • 2017-03-02
    • 2018-06-02
    相关资源
    最近更新 更多