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

问题描述 投票:0回答:1

我有三种型号:

  • 用户
  • 图像
  • 发布

和他们的关系是:

  • 用户有很多图像,
  • 图像属于用户,
  • 用户有很多帖子,
  • 发布属于用户,

如何使用查询生成器来查询关系,直到获得下面的数据?

user_name: name,
image: [
  {
    ... 
  },
  {
   ...
  }
],
post: [
  {
   ...
  },
  {
   ...
  }
]```
mysql laravel laravel-query-builder
1个回答
0
投票
$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);

© www.soinside.com 2019 - 2024. All rights reserved.