【问题标题】:Laravel Get data from relationship's relationship table and select column?Laravel 从关系的关系表中获取数据并选择列?
【发布时间】: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


【解决方案1】:

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

【讨论】:

  • 在这种情况下如何从“Post”中仅获取少数属性或为 Post 中的少数列设置别名?
  • 只获取几个属性:Post::with(bla bla bla)->select([field_name1, field_name2])->where(bla bla bla);。选择时不要忘记包含所需的外键。
猜你喜欢
  • 1970-01-01
  • 2021-08-06
  • 2020-07-01
  • 2018-02-14
  • 1970-01-01
  • 2021-12-24
  • 2015-11-29
  • 2013-04-03
  • 1970-01-01
相关资源
最近更新 更多