【问题标题】:Laravel Spatie Query Builder - Wrong query when make joinLaravel Spatie Query Builder - 加入时查询错误
【发布时间】:2021-08-20 00:37:26
【问题描述】:

我对 spatie/Laravel-query-builder 包有疑问。我使用这个包来简单地过滤和排序我的查询,但它不是那样的:D

我试图过滤有两个关系的结果 - 商店和员工。简而言之,它想过滤商店报告列表

看,这是我的代码。当我使用 join 方法时,作为响应,会收到 ID 不正确的数据。当评论加入方法时一切正常,但我需要按关系排序。

return ReportControlResource::collection(
            QueryBuilder::for(Report::class)
                ->with(['employee', 'shop'])
                ->allowedFilters('shop.name', 'employee.name')
                ->join('employees', 'employees.id', '=', 'reports.employee_id')
                ->join('shops', 'shops.id', '=', 'reports.shop_id')
                ->allowedSorts(['employees.name'])
                ->get()
        );

我在报告模型中的关系:

public function shop(): BelongsTo
    {
        return $this->belongsTo(Shop::class);
    }

    public function employee(): BelongsTo
    {
        return $this->belongsTo(Employee::class);
    }

Shop 模型中的关系:

public function reports()
    {
        return $this->hasMany(Report::class);
    }

在员工模型中

public function reports()
    {
        return $this->hasMany(Report::class);
    }

你有什么想法吗?

我注意到ID被覆盖了,但不是shop_id和employee_id,但是ID为什么??

我认为问题出在图书馆本身。创建者没有考虑到我的情况下加入表格的相反情况。

查看文档中的示例:

$addRelationConstraint = false;

QueryBuilder::for(User::class)
    ->join('posts', 'posts.user_id', 'users.id')
    ->allowedFilters(AllowedFilter::exact('posts.title', null, $addRelationConstraint));

我的加入

->join('employees', 'employees.id', '=', 'reports.employee_id')

但是这个加入是这样工作的

->join('employees', 'reports.id', '=', 'reports.employee_id')

但是为什么呢?我通过多种方式检查了订单,甚至断开了过滤,它没有改变任何东西

【问题讨论】:

    标签: php laravel eloquent relation laravel-query-builder


    【解决方案1】:

    我找到了问题的解决方案。我必须选择一列,现在一切正常:-)

    return EvidenceControlResource::collection(
                QueryBuilder::for(EvidenceControl::class)
                    ->allowedIncludes('employee', 'shop')
                    ->select('evidence_controls.*', DB::raw('employees.id as employee_id'))
                    ->join('employees', 'evidence_controls.employee_id', '=', 'employees.id')
                    ->select('evidence_controls.*', DB::raw('shops.id as shop_id'))
                    ->join('shops', 'evidence_controls.shop_id', '=', 'shops.id')
                    ->allowedFilters('shop.name', 'employee.name')
                    ->allowedSorts(['employees.name', 'shops.name'])
                    ->get()
            );
    

    这不是干净的代码,但是当使用实现排序创建自己的类时,代码看起来会好很多。

    感谢盖伊的帮助!祝你好运! :-)

    【讨论】:

      猜你喜欢
      • 2020-09-01
      • 1970-01-01
      • 2019-04-19
      • 2021-01-18
      • 1970-01-01
      • 2013-03-19
      • 1970-01-01
      • 2021-10-05
      • 2015-10-29
      相关资源
      最近更新 更多