mysql - 如何使用查询构建器在 Laravel 中使用关系查询我的模型
问题描述
我有三个模型:
- 用户
- 图片
- 邮政
他们的关系是:
- 用户有很多图像,
- 图片属于用户,
- 用户有很多帖子,
- 帖子属于用户,
在获得以下数据之前,如何使用查询生成器查询关系?
user_name: name,
image: [
{
...
},
{
...
}
],
post: [
{
...
},
{
...
}
]```
解决方案
$user = User::find(1);
$images = $user->images // images is function name as u added in relationship
$posts = $user->posts // posts is function name as u added in relationship
$response = [
'user_name' => $user->name,
'images' => $images,
'posts' => $posts,
];
return response($response);
你也可以使用
$user = User::with(['images','posts'])->find(1);