1

I have 3 models: Article, Comment, Reaction.

Each article has many comments, and each comment has many reactions:

App\Article:

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

App\Comment:

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

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

App\Reaction:

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

In my ArticleController@index I want to fetch comments and their reactions:

ArticleController:

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

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

I can loop through the comments ($article->comments), however I'm not sure how to do a with('reactions') for the comments? i.e.,

@foreach($article->comments as $comment)
    @foreach($comment->reactions)
        // something like this...
    @endforeach
@endforeach
2
  • Is it really necessary to use the with method? You can just as easily get all the articles using Articles::all(); Commented Oct 12, 2016 at 8:48
  • @Adherence - didn't know it joined them automatically with the all() method, thanks! Commented Oct 12, 2016 at 9:46

2 Answers 2

1

you can do Nested Eager Loading

$article = Article::with('comments.reactions')
                ->leftjoin('comments', 'comments.article_id', '=', 'articles.id')
                ->select('articles.*')
                ->get();
Sign up to request clarification or add additional context in comments.

2 Comments

What about the reactions?
@frosty check now,added articles by mistake
0

You can also do this way

ArticleController:

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

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

App\Article:

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

App\Comment:

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.