【问题标题】:Unable to structure raw query in to array无法将原始查询构造到数组中
【发布时间】:2019-09-30 21:38:08
【问题描述】:

我有一个资源类和一个控制器,我正在做一些像这样的原始查询。我曾尝试使用json_encode()json_decode(),但我不断收到错误。

*Json_decode

Call to a member function first() on null

*Json_encode

Call to a member function first() on string

*只需返回 $test_table *

Call to undefined method stdClass::toArray()

TestsController.php

use App\Test;
use App\Http\Resources\Test as TestResource;

public function index()
{
    $test_table = DB::table('test_table')->select('id','test_col')->paginate(10);

    return  TestResource::collection($test_table);           
}

*资源/测试

class Test extends JsonResource
{
    /**
     * Transform the resource into an array.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array
     */
    public function toArray($request)
    {
        return parent::toArray($request);
    }
}

预期的输出应该是我可以在前端应用程序中处理的 JSON,使用 GuzzleHttp 也应该能够很好地分页。

【问题讨论】:

  • 你在哪里使用json_encode()

标签: php laravel api laravel-5


【解决方案1】:

我认为问题与在 select 语句之后使用分页有关。鉴于您正在使用 API 资源,您可以只返回您想要的数据:

TestsController.php

use App\Test;
use App\Http\Resources\Test as TestResource;

// ...

    public function index()
    {
        $results = DB::table('test_table')->paginate(10);
                           /**       ^^^^^^^     */

        return  TestResource::collection($results);           
    }

然后在您的资源中:

资源/Test.php

class Test extends JsonResource
{
    /**
     * Transform the resource into an array.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array
     */
    public function toArray($request)
    {
        return [
            'id' => $this->id,  // <------
            'test_col' => $this->test_col,  // <------
        ];
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-01-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-03
    相关资源
    最近更新 更多