2015-10-10 33 views
0

我嘗試使用hasManyThrough嘗試加載相關模型時發生了一些奇怪的事情。Laravel - hasManyThrough和急切的加載,從相關的列中獲取

我有一個社區模型,它有一個名爲'室友'的功能,讓所有在社區中有社區ID的用戶名爲'community',見下面的代碼。

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

那麼用戶模型是從驗證登錄和渴望加載後搶下相關車型,並且只顯示我想要的列。 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": "[email protected]", 
"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": "[email protected]" 
    }, 
    { 
     "id": 1, 
     "name": "Foo Bar", 
     "email": "[email protected]" 
    } 
    ] 
}, 
"remember_token": "tprkiNOYbBiViwQkVcJMcwU8poZ1/00Uktmy7AQ+", 
"created_at": "2015-10-09 08:03:42", 
"updated_at": "2015-10-10 04:56:14" 
} 
} 

正如你所看到的ID在這兩個用戶的室友陣列中是1,但是這些用戶的ID是2個3

任何想法?

我還在感覺Laravel,所以我不知道該從哪裏出發?

回答

0

結束了工作出來,

我改變,而不是使用hasManyThrough

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

的hasMany同時,我需要選擇外鍵,community_id,否則我會得到一個空的結果。

積分這個問題幫我弄明白

Laravel Eager Loading - Load only specific columns