【发布时间】:2018-10-01 07:30:57
【问题描述】:
我有 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();
【问题讨论】:
-
所以你的意思是你想摆脱
user表,对吧? -
不,我想通过 user.userDetail 关系访问 user_details 表的 first_name 和 last_name 列(user_details 表中有更多列我没有在此处添加)当前它从 user_details 和 user 表返回整个列
-
试试(['city:id,name_en', 'user.userDetail' => function($query){$query->select('first_name', 'last_name', 'id' )}]);
-
@fatemehMajd 它为 user_detail 返回 null
-
因为
user_id必须在选择查询中,因为它是外键。这就是结果为空的原因
标签: php laravel eloquent laravel-5.7