frosty
frosty

Reputation: 2851

Laravel "nested" with()

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

Upvotes: 1

Views: 163

Answers (2)

Ronak Dattani
Ronak Dattani

Reputation: 466

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');
    }
}

Upvotes: 0

StateLess
StateLess

Reputation: 5402

you can do Nested Eager Loading

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

Upvotes: 1

Related Questions