Laravel 空间查询生成器

Laravel Spatie Query Builder

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

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

查看该图书馆后,这就是我所拥有的。

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

请注意,现在包中原生支持此功能。

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