L
L
legolas44442014-10-28 15:49:20
Laravel
legolas4444, 2014-10-28 15:49:20

How to get posts with comments in Laravel 4?

You need to get records with comments by type like VK. That is, the cycle displays posts and 3 last comments to them. I do this:
In the Posts model:

public function lastcomments()
    {
        return $this->hasMany('Comment')->orderBy('created_at','DESC')->limit(3);
    }

And the request itself:
$arr = array(1,2,3 ...)
Post::whereIn('id',$arr)->orderBy('id', 'desc')->with("lastcomments")->get();

But this code gets the last 3 comments not for each post, but for all . That is, if I display 10 posts, then theoretically 30 comments should be selected, and only 3 are selected.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
Y
Yuri Mostovoy, 2014-10-28
@PROGRAMMATOR

With active loading, you won't.

F
FanatPHP, 2014-10-28
@FanatPHP

I was wrong, I apologize.
This is a fundamental limitation for eager loading, and the current behavior is the only thing it can provide. That is, there is no point in using hasMany here.
That is, comments must be received in separate requests, according to the number of posts, which brings us back to the previous denormalization task. Although I would not be in a hurry to do it, since 20 queries on the index will not load the database.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question