我是新來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
}
}
但我想知道如何獲得評論未做僅使用關係這些循環。提前致謝。
$ post-> comments將返回一系列評論。然後你可以調用toArray(),或者如果你只需要數組中的一個字段,可以使用pluck,例如:$ post-> comments-> pluck('title','id') ; – Steven1978
https://laravel.com/docs/5.2/collections#method-toarray – Steven1978