2016-02-05 149 views
3

我是新來laravel和我使用Laravel 5.2我想擁有一個用戶的特定職位的所有評論。我的桌子是這樣的:Laravel 5.2渴望加載多個一級可能的關係

User 
----- 
id 

public function posts() { 
    $this->hasMany('App\Posts') 
} 

Post 
------ 
id 
user_id 

public function user() { 
    $this->belongsTo('App\User') 
} 

public function comments() { 
    $this->hasMany('App\Comment') 
} 

Comments 
---------- 
id 
post_id 

public function post() { 
    $this->belongsTo('App\Post') 
} 

現在我想要的是獲得一個特定用戶的所有帖子說的登錄用戶。我可以用很長的路要走得到所有的意見,如:

$comments = []; 
foreach(Auth::user()->posts as $post) { 
    foreach($post->comments as $comment) 
    { 
     $comments[] = $comment->title 
    } 
} 

但我想知道如何獲得評論未做僅使用關係這些循環。提前致謝。

+0

$ post-> comments將返回一系列評論。然後你可以調用toArray(),或者如果你只需要數組中的一個字段,可以使用pluck,例如:$ post-> comments-> pluck('title','id') ; – Steven1978

+0

https://laravel.com/docs/5.2/collections#method-toarray – Steven1978

回答

0

您可以雙擊與現有用戶對象的關係:

$posts = \Auth::user()->posts()->with('comments')->get(); 

它應該適用於所有級別。

在項目中,我組織與一個鏈接表治療師,所有的多個客戶端,這一點也適用:

Organization::find(1)->clients()->with('therapists')->get(); 

所以你的情況應該工作了。讓我知道。

+0

感謝Rudie的工作。 – Pranab

0

基本上你想渴望負載使用with()和點符號,像這樣數據:

$user = User::with('posts.comments')->find(Auth::user()->id); 

如果你只是想的意見,你可以這樣做:

$user = User::with('comments')->find(Auth::user()->id); 
$comments = $user->comments();