首页 > 解决方案 > 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();

标签: phplaraveleloquentlaravel-5.7

解决方案


这将获取所有“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();

推荐阅读