Lumen 要記得配置 config

wonderfate發表於2020-11-10

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`.
:exclamation:但是看錯誤提示是沒有任何問題的

Lumen 沒有配置 bootstrap/app.php 的記錄

追蹤原始碼

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 協議》,轉載必須註明作者和本文連結

相關文章