使用关系格式化Laravel JSON对象

时间:2016-04-13 18:56:26

标签: json laravel collections models

我的目标是为这样的API输出JSON:

[
    {
        "id": 3,
        "name": "QUbkaUJhNm",
        "email": "w6KYFZnypT@gmail.com",
        "created_at": null,
        "updated_at": null,
        "profile": {
            "a": "value",
            "b": "value",
            "c": "value"
        }
    },
    {
        "id": 5,
        "name": "lYXmtkKuX9",
        "email": "yu3dob2lyH@gmail.com",
        "created_at": null,
        "updated_at": null,
        "profile": {
            "a": "value",
            "b": "value",
            "c": "value"
        }
    }
]

我有两个模特。

用户模型:

public function profile() 
{
     return $this->hasOne(Profile::class);
}

个人资料模型:

public function user() 
{
     return $this->belongsTo(User::class);
}

我的API控制器的代码应该是什么?

$users = User::all();

...

谢谢!

1 个答案:

答案 0 :(得分:2)

您可以像这样使用Eager Loading:

return User::with('profile')->get();

如果你想要结果paginate

return User::with('profile')->paginate();