2017-08-01 96 views
0

在我的崗位型號屬性[***]不能在此集合實例Laravel雄辯關係存在

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

和用戶模式

public function posts() 
{ 
    return $this->hasMany('App\Post'); 
} 

現在我想獲得的評論特定用戶的

$user= User::where('name', 'like', '%Mat%')->first(); 
return $user->posts->comment; 

但它顯示

屬性[註釋]在此收集實例中不存在。

回答

2

因此,用戶has many posts因此返回一個集合,您將需要遍歷此以獲取您的評論。即

$user = User::where('name', 'like', '%Mat%')->first(); 

$user->posts->each(function($post) { 
    echo $post->comment; 
}); 

documentation on Laravel Collections

0

我想你可以試試這個:

$user= User::with('post')->where('name', 'like', '%Mat%')->get(); 

$postComment = array(); 

foreach($user->post as $post){ 
    $postComment = $post->comment; 
} 
return $postComment; 

希望這有助於爲你!

0

如果你想擁有所有評論,你可以使用下面的代碼:

$comments = []; 

$user = User::where('name', 'like', '%Mat%')->with(['post.comment' => function($query) use (&$comments) { 
    $comments = $query->get(); 
}])->first(); 

return $comments; 
0

地產[評論]不會對這種集合實例存在。

發生上述錯誤是因爲Posts函數返回一個集合。現在您將不得不遍歷集合中的每個元素。因爲您正在返回$ user-> posts() - > comment,我假設您需要它以數組的形式,並且不必一個接一個地將它們回顯出來。所以你可以將它們全部存儲在一個數組中&然後處理它,無論你喜歡什麼。

$comments = array(); 
$user->posts()->each(function $post){ 
    $comments = $post->comment; 
} 
return $comments; 

進行更深入,這個集合函數read: https://laravel.com/docs/5.4/collections#method-each