Laravel REST API获取具有关系的模型

时间:2020-06-28 11:36:32

标签: laravel rest

我正尝试通过以下方式检索模型:

        _id: 1, // ====> The model (example: Message)
          text: 'My message',
          createdAt: new Date(Date.UTC(2016, 5, 11, 17, 20, 0)),
          user: { // ====> The model in the relationship, in this case, the USER
            _id: 2,
            name: 'React Native',
            avatar: 'https://facebook.github.io/react/img/logo_og.png',
          },

我怎么可能用laravel做到这一点?

我当前的代码如下:

public function show($id){
        $id = Group::where('id', $id)->first();
        return response()->json([
            'messages' => $id->messages,
        ]);
    }

1 个答案:

答案 0 :(得分:1)

您应该看一下JSON资源:https://laravel.com/docs/7.x/eloquent-resources

您可以像这样编写资源:

<?php

namespace App\Http\Resources;

use Illuminate\Http\Resources\Json\JsonResource;

class Group extends JsonResource
{
    /**
     * @param  \Illuminate\Http\Request  $request
     * @return array
     */
    public function toArray($request)
    {
        return [
            '_id' => $this->id,
            'text' => $this->text,
            'createdAt' => $this->created_at,
            // define the User resource too
            'user' => UserResource::collection($this->users)
        ];
    }
}

然后只需使用:

// use model binding here, it will retrieve your model from the ID
public function show(Group $group)
{
    return new GroupResource($group);
}