如何使用查询生成器在 Laravel 中查询我的模型与关系

How to query my model in Laravel with relationships using query builder

我有三个模型:

他们的关系是:

如何使用 query builder 查询关系,直到获得以下数据?

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);