Lumen 要记得配置 config
Lumen 试用 Laravel-query-builder ,文档没有 Lumen 的安装教程,我一直忘了 config 文件配置
重要的事情说三遍
Lumen 装扩展包一定要看是否有 config,需要在 bootstrap/app.php 配置
Lumen 装扩展包一定要看是否有 config,需要在 bootstrap/app.php 配置
Lumen 装扩展包一定要看是否有 config,需要在 bootstrap/app.php 配置
出现错误
代码
API:localhost/orders?include=user,items
控制器:
public function index(Request $request)
{
$orders = QueryBuilder::for(Order::class)
->allowedIncludes(['user', 'items.product'])
->paginate();
return OrderResource::collection($orders);
}
提示
Requested include(s) `user,items` are not allowed. Allowed include(s) are `user, items, items.product`.
但是看错误提示是没有任何问题的
追踪源码
Spatie\QueryBuilder\QueryBuilderRequest.php
public function includes(): Collection
{
$includeParameterName = config('query-builder.parameters.include');
$includeParts = $this->query($includeParameterName);
// 这个类继承 Illuminate\Http\Request
// $this->query() 应该是获取到数据的,访问 ?include=user,items 打印出来的都是数组(为何是数组详情看 $this->query() 源码,当获取不到形参时拿所有的参数作为数组)
// 所以再试试 $includeParameterName 得到的是什么
// $includeParameterName 为空,config('query-builder.parameters.include') 获取不到配置文件
// 原因是 https://learnku.com/docs/lumen/6.x/configuration/6102#36c577
if (! is_array($includeParts)) {
$includeParts = explode(static::getIncludesArrayValueDelimiter(), $this->query($includeParameterName));
}
return collect($includeParts)
->filter()
->map([Str::class, 'camel']);
}
Spatie\QueryBuilder\Concerns\AddsIncludesToQuery.php
protected function ensureAllIncludesExist()
{
// 调用 Spatie\QueryBuilder\Concerns\AddsIncludesToQuery.php 的 includes
// 获取到的 include 参数,结果应该是 Array
// 但是这里总是拿到一个字符串
$includes = $this->request->includes();
$allowedIncludeNames = $this->allowedIncludes->map(function (AllowedInclude $allowedInclude) {
return $allowedInclude->getName();
});
$diff = $includes->diff($allowedIncludeNames);
if ($diff->count()) {
throw InvalidIncludeQuery::includesNotAllowed($diff, $allowedIncludeNames);
}
// TODO: Check for non-existing relationships?
}
本作品采用《CC 协议》,转载必须注明作者和本文链接
推荐文章: