无法将原始查询构造到数组中

时间:2019-05-13 22:25:40

标签: php laravel api laravel-5

我有一个资源类和一个控制器,我正在像这样做一些原始查询。我曾尝试使用import pandas as pd from sklearn import metrics df = pd.read_csv("master.csv") labels = list(df['Q3 Theme1']) X = open('entire_dataset__resnet50_feature_vectors.txt') #X_Data = X.read() fv = [] for line in X: line = line.strip("\n") tmp_arr = line.split(' ') print(tmp_arr) fv.append(tmp_arr) print(fv) print('Silhouette Score:', metrics.silhouette_score(fv, labels, metric='cosine')) json_encode(),但是我总是遇到错误。

* Json_decode

json_decode()

* Json_encode

Call to a member function first() on null

*仅返回$ test_table *

Call to a member function first() on string

TestsController.php

Call to undefined method stdClass::toArray()

*资源 / 测试

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

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

1 个答案:

答案 0 :(得分:0)

我认为问题与在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,  // <------
        ];
    }
}