php - Laravel 从关系的关系表中获取数据并选择列?
问题描述
我有 3 张桌子
用户表
+----+-------+----------+
| id | email | password |
+----+-------+----------+
| 1 | 1 | John |
+----+-------+----------+
user_details 表
+----+--------------------+------------+-----------+
| id | user_id [FK_users] | first_name | last_name |
+----+--------------------+------------+-----------+
| 1 | 1 | John | Kevin |
+----+--------------------+------------+-----------+
帖子表
+----+--------------------+----------+
| id | user_id [FK_users] | title |
+----+--------------------+----------+
| 1 | 1 | 1st Post |
+----+--------------------+----------+
现在我已经在模型中创建了所有关系,现在我可以通过下面的 eloquent 查询访问 user_details 表,它返回整个用户表和 user_details 表,但我只想从 user_details 表中选择 first_name 和 last_name 我该怎么做?
$posts= Post::with('city:id,name_en', 'user.userDetail')->where('id', $id)->get();
解决方案
这将获取所有“post”属性,“user” id
,“user_details”user_id, first_name, last_name
$posts= Post::with([
'city:id,name_en',
'user' => function ($query) {
$query->select('id');
},
'user.userDetail' => function($query) {
$query->select(['user_id', 'first_name', 'last_name']);
}
])->where('id', $id)->get();
推荐阅读
- r-caret - 为什么在插入符号的 trainControl 函数中使用时间片方法时 RMSE 会随着地平线增加?
- ruby-on-rails - 我应该为带有 Vue.js 前端的 SPA Rails 应用程序使用两台服务器吗?
- javascript - selectize - 未捕获的类型错误:$(...).selectize 不是函数
- python - 使用类参数中的条件对类对象列表进行排序
- generics - 具有泛型类型结构值的结构
- android - 用于地图应用的最佳跨平台技术(iPhone、Android)
- jquery - 通过滚动动画 jquery 卷轴
- pandas - read_csv 没有分隔给定 txt 文件中的列
- laravel - 是否有在 Laravel 中存储图像(主题和上传)的正确路径?
- ios - 使用多种颜色设置 UIImageView tintColor