我的目标是像这样为 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 Controller 的代码应该是什么?
$users = User::all();
...
谢谢!
最佳答案
您可以像这样使用预加载:
return User::with('profile')->get();
如果你想要结果分页
return User::with('profile')->paginate();
关于json - 使用关系格式化 Laravel JSON 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36607190/