【问题标题】:Laravel - hasManyThrough and eager loading, get column from relatedLaravel - hasManyThrough 和急切加载,从相关获取列
【发布时间】:2016-01-08 03:04:39
【问题描述】:

在尝试使用 hasManyThrough 急切加载相关模型时,我遇到了一些奇怪的事情。

我有一个社区模型,它有一个名为“室友”的功能,可以在名为“社区”的列中获取所有具有社区 ID 的用户,请参见下面的代码。

    public function roommates()
    {
        return $this->hasManyThrough('App\User', 'App\Community', 'id', 'community');
    }

然后在登录后从 Auth 中抓取 User 模型并急切加载相关模型,并且只显示我想要的列。 ID、姓名、电子邮件

$user = User::where('id', Auth::id())->with(['community.roommates' => function ($query) 
        {
            $query->select('users.id', 'name', 'email');
        }])->first();

但是我的 JSON 响应不是我所期望的,返回的 id 似乎是社区的 id,即使我指定了“users.id”

{
"status": true,
"data": {
"id": 3,
"name": "Foo Bar",
"email": "test@test.com",
"community": {
  "id": 1,
  "owner": 3,
  "title": "Home",
  "created_at": "2015-10-09 08:04:05",
  "updated_at": "2015-10-09 08:04:05",
  "roommates": [
    {
      "id": 1,
      "name": "Foo Bar 2",
      "email": "test@test.com"
    },
    {
      "id": 1,
      "name": "Foo Bar",
      "email": "test@test.com"
    }
  ]
},
"remember_token": "tprkiNOYbBiViwQkVcJMcwU8poZ1/00Uktmy7AQ+",
"created_at": "2015-10-09 08:03:42",
"updated_at": "2015-10-10 04:56:14"
}
}

如您所见,roommates 数组中两个用户的 id 都是 1,但是这些用户的 id 是 2 和 3。

有什么想法吗?

我仍然在使用 Laravel,所以我不知道从哪里开始?

【问题讨论】:

    标签: php laravel eloquent loading eager


    【解决方案1】:

    最终解决,

    我改用 hasMany 而不是 hasManyThrough

        public function roommates()
        {
            return $this->hasMany('App\User', 'community_id', 'id')->select(['community_id', 'id', 'name', 'email']);
        }
    

    而且我还需要选择外键 community_id,否则我会得到一个空白结果。

    感谢这个问题帮助我弄清楚

    Laravel Eager Loading - Load only specific columns

    【讨论】:

      猜你喜欢
      • 2021-10-08
      • 2013-06-10
      • 2019-09-19
      • 1970-01-01
      • 2014-11-12
      • 2018-04-28
      • 2021-11-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多