首页 > 解决方案 > 如何使用查询构建器在 Laravel 中使用关系查询我的模型

问题描述

我有三个模型:

他们的关系是:

在获得以下数据之前,如何使用查询生成器查询关系?

user_name: name,
image: [
  {
    ... 
  },
  {
   ...
  }
],
post: [
  {
   ...
  },
  {
   ...
  }
]```

标签: mysqllaravellaravel-query-builder

解决方案



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


推荐阅读