Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/json/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用关系格式化Laravel JSON对象_Json_Laravel_Collections_Models - Fatal编程技术网

使用关系格式化Laravel JSON对象

使用关系格式化Laravel JSON对象,json,laravel,collections,models,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",

我的目标是为如下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);
}
我的ApicController的代码应该是什么

$users = User::all();

...

谢谢大家!

您可以像这样使用即时加载:

return User::with('profile')->get();
如果您想要结果,请分页

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

现在让我们假设
profile
有它自己的关系,我怎样才能渲染它们呢?示例:
User->profile()->phoneNumber()