格式化 Laravel JSON 具有关系的对象
Formatting Laravel JSON Object with relations
我的目标是像这样为 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();
...
谢谢!
您可以像这样使用预加载:
return User::with('profile')->get();
如果你想要结果分页
return User::with('profile')->paginate();
我的目标是像这样为 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();
...
谢谢!
您可以像这样使用预加载:
return User::with('profile')->get();
如果你想要结果分页
return User::with('profile')->paginate();