Laravel与()嵌套“

时间:2016-10-12 08:43:11

标签: php laravel

我有3个模型:ArticleCommentReaction

每篇文章都有很多评论,每条评论都有很多反应:

应用\文章:

class Article extends Model
{
    public function comments() {
        return $this->hasMany('App\Comment');
    }
}

应用\评论:

class Comment extends Model
{
    public function article() {
        return $this->belongsTo('App\Article');
    }

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

应用\反应:

class Reaction extends Model
{
    public function comment() {
        return $this->belongsTo('App\Comment');
    }
}

在我的ArticleController@index我想提取评论及其反应:

ArticleController:

public function index()
{
    $articles = Article::with('comments')
                ->select('articles.*')
                ->leftjoin('comments', 'comments.article_id', '=', 'articles.id')
                ->get();

    return view('wiki')->withArticles($articles);
}

我可以循环浏览评论($article->comments),但是我不确定如何为评论做with('reactions')?即,

@foreach($article->comments as $comment)
    @foreach($comment->reactions)
        // something like this...
    @endforeach
@endforeach

2 个答案:

答案 0 :(得分:1)

你可以Nested Eager Loading

$article = Article::with('comments.reactions')
                ->leftjoin('comments', 'comments.article_id', '=', 'articles.id')
                ->select('articles.*')
                ->get();

答案 1 :(得分:0)

您也可以这样做

<强> ArticleController:

 public function index()
    {
        $articles = Article::with('comments')
                    ->select('articles.*')
                    ->get();

        return view('wiki')->withArticles($articles);
    }

应用\文章:

class Article extends Model
{
    public function comments() {
        return $this->hasMany('App\Comment')->with('reactions');
    }
}

应用\评论:

class Comment extends Model
{
    public function article() {
        return $this->belongsTo('App\Article');
    }

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