【问题标题】:Format result for requesting all data请求所有数据的格式化结果
【发布时间】:2022-01-20 11:46:49
【问题描述】:

我的控制器带有index()show()

{
    /**
     * Display a listing of the resource.
     *
     * @return \App\Http\Resources\MyRessource
     */
    public function index()
    {
        //???
    }


    /**
     * Display the specified resource.
     *
     * @param  \App\Models\Test  $test
     * @return \App\Http\Resources\TestRessource
     */
    public function show(Test $test)
    {
        return new \App\Http\Resources\TestRessource($test);
    }
}

在我的资源中,show() 具有我想要返回的格式,因此http://127.0.0.1/Test/1 的结果是带有格式化 JSON 的 ID 1。

{
    "data": {
        "id": 1,
        "ref": "0103573026466442101007175850",
        "tax": null,
        "date_in": "2021-10-08T12:37:05.000000Z",
        "date_out": "2021-10-11T08:02:17.000000Z"
    }
}

我希望index() 使用我的资源以相同的方式返回。 当我在 http://127.0.0.1/Test 上执行 index() 时,它会返回我的所有数据,但不是我想要的格式化 JSON。

资源代码:

{
    /**
     * Transform the resource into an array.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array|\Illuminate\Contracts\Support\Arrayable|\JsonSerializable
     */
    public function toArray($request)
    {
        return [
            "id" => $this->id,
            "ref" => $this->ref,
            "tax" => $this->tax,
            "date_in" => $this->date_in,
            "date_out" => $this->date_out
        ];
    }

【问题讨论】:

    标签: php laravel-8 laravel-eloquent-resource


    【解决方案1】:

    index() 上执行docs 中的操作。

    return TestRessource::collection(Test::all());
    

    【讨论】:

    • 谢谢它的工作,但是当我有很多数据时,它非常非常慢。超过2分钟。是否可以对这个结果进行分页?
    • 我想我找到了解决办法:return TestRessource::collection(Test::query()->paginate(20));
    • @Franck 你可以做Test::paginate(20)
    猜你喜欢
    • 1970-01-01
    • 2012-01-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-28
    相关资源
    最近更新 更多