【问题标题】:Laravel Spatie Query BuilderLaravel Spatie 查询生成器
【发布时间】:2018-11-27 20:39:51
【问题描述】:

在我的用户控制器的索引中,我有以下内容:

return QueryBuilder::for(User::class)
    ->with('phoneNumbers')
    ->allowedIncludes('trashed')
    ->get();

我希望像这样传递一个包含参数:

http://127.0.0.1:8000/v1/users?include=trashed

withTrashed() 全局范围附加到查询。

这可能吗?我很可能遗漏了一些明显的东西,我在测试中尝试了一些变体,通常会出现如下错误:

"message": "Call to a member function addEagerConstraints() on boolean",
    "exception": "Symfony\\Component\\Debug\\Exception\\FatalThrowableError",
    "file": "/Users/timwickstrom/Sites/Wavefire/api/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Builder.php",
    "line": 522,

供参考: https://github.com/spatie/laravel-query-builderenter link description here

【问题讨论】:

  • 检查phoneNumbers是否存在或返回类User的关系
  • 你不能用withTrashed()吗?我认为这是问题所在,当您在allowedIncludes 中使用它时,它被视为关系。

标签: php laravel laravel-5 laravel-query-builder


【解决方案1】:

在查看了那个库之后,这就是我所拥有的。

return QueryBuilder::for(User::class)
    ->with('phoneNumbers') // <-- I think you can use `allowedIncludes` here.
    ->allowedFilters([ // <-- I believe that `withTrashed` is a scope query,
                       // so you can use this. You cannot use `allowedIncludes`
                       // because it works with relations.
        Filter::scope('withTrashed')
    ])
    ->get();

【讨论】:

  • 感谢您的发帖。阅读本文并重新阅读文档后,我仍然无法让它包含全局 withTrashed。我尝试通过它?filter['trashed'],?filter['withTrashed'],?filter['with_trashed']。从来没有加过。但它确实给了我如何解决它的灵感。所以谢谢你。
  • 实际上这确实有效!谢谢你。在我测试过滤器的值时,有一个缺失的部分。 withTrashed 不包括参数,但您仍然需要像这样传递 true:127.0.0.1:8000/v1/users?filter[withTrashed]=true
  • 它工作得很好!抱歉,我对 url 的东西一无所知,它包含在库中吗?
  • 不,这是我定义的用于测试的路线。这部分 ?filter[withTrashed]=true 是您与 QueryBuilder 交互的方式。我只是传递了 ?filter[withTrashed] ,它没有触发查询生成器。当我添加 =true 或 =1 时,它将包括范围。
【解决方案2】:

一个迟到的说明,这个包现在原生支持。

https://spatie.be/docs/laravel-query-builder/v5/features/filtering

QueryBuilder::for(Booking::class)
    ->allowedFilters([
        AllowedFilter::trashed(),
    ]);

// GET /bookings?filter[trashed]=only will only return soft deleted models

【讨论】:

    猜你喜欢
    • 2021-06-26
    • 2015-12-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-10
    • 2019-01-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多