Laravel分页与关系

时间:2019-05-10 22:14:05

标签: laravel orm eloquent

这是我的代码:

public function divisions(Request $request)
{
    $q = $request->get('q');

    return Division::where('name', 'like', "%$q%")
            ->with(['nation' => function($query) {
                $query->select('id', 'name');

            }])->simplePaginate();
}

并返回以下内容:

{
    "id": 1,
    "name": "1",
    "classify": 1,
    "nation_id": 1,
    "user_id": 1,
    "created_at": "2019-05-08 09:00:00",
    "updated_at": "2019-05-08 09:00:00",
    "nation": {
        "id": 1,
        "name": "France"
    }
}

但是我需要以下内容。我该怎么做才能只返回以下内容?

{
    "id": 1,
    "name": "1",
    "nation": "France"
}

谢谢

2 个答案:

答案 0 :(得分:1)

如果使用它来构建API,则可以使用Eloquent API Resources,因此可以将其用作以下内容:

public function toArray($request)
{
    return [
        'id' => $this->id,
        'name' => $this->name,
        'nation' => $this->nation->name,
    ];
}

答案 1 :(得分:1)

尝试以下给出的答案,我认为这将帮助您实现问题的解决方案。

解决方案1:

public function divisions(Request $request)
{
    $string = $request->get('q');
    $builder = new Division;
    $builder->where('name', LIKE, "%$string%")
            ->with(['nation' => function($query) {
                $query->select('id', 'name');
            }]);

    $result = $builder->selectRaw("id, name, nation.name as nation")->simplePaginate();

    return response()->json($result);
}

解决方案2

在控制器中

public function divisions(Request $request)
{
    $string = $request->get('q');
    $builder = new Division;
    $builder->where('name', LIKE, "%$string%")
            ->with(['nation' => function($query) {
                $query->select('id', 'name');
            }]);

    $paginator = $builder->paginate();

    $data = fractal()
                ->collection($paginator->getCollection(), new DivisionsTransformer, 'divisions')
                ->serializeWith(new DataArraySerializer())
                ->paginateWith(new IlluminatePaginatorAdapter($paginator))
                ->toArray();
}

部门变形金刚

public function transform($resource)
{
    return [
        'id' => $resource->id,
        'name' => $resource->name,
        'nation' => $resource->nation->name,

    ];
}

这里是变压器库的参考。 https://github.com/spatie/laravel-fractal