Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/246.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php Laravel-有许多粗略而急切的加载,从相关的_Php_Laravel_Eloquent_Loading_Eager - Fatal编程技术网

Php Laravel-有许多粗略而急切的加载,从相关的

Php Laravel-有许多粗略而急切的加载,从相关的,php,laravel,eloquent,loading,eager,Php,Laravel,Eloquent,Loading,Eager,在尝试使用hasManyThrough加载相关模型时,我遇到了一些奇怪的事情 我有一个社区模型,它有一个名为“roommates”的函数,用于获取在名为“Community”的列中具有社区id的所有用户,请参见下面的代码 public function roommates() { return $this->hasManyThrough('App\User', 'App\Community', 'id', 'community'); } 然后在登录

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

我有一个社区模型,它有一个名为“roommates”的函数,用于获取在名为“Community”的列中具有社区id的所有用户,请参见下面的代码

    public function roommates()
    {
        return $this->hasManyThrough('App\User', 'App\Community', 'id', 'community');
    }
然后在登录后从Auth抓取用户模型,并立即加载相关模型,只显示我想要的列。身份证、姓名、电子邮件

$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

有什么想法吗


我仍在和拉威尔交往,所以我不知道该从这里走到哪里去?

最终解决了这个问题

我改用hasMany而不是hasManyThrough

    public function roommates()
    {
        return $this->hasMany('App\User', 'community_id', 'id')->select(['community_id', 'id', 'name', 'email']);
    }
我还需要选择外键、社区id,否则我会得到一个空白结果

这道题的功劳帮助我解决了这个问题