$posts->comments()->links(); gives following error:
ErrorException
call_user_func_array() expects parameter 1 to be a valid callback, class 'Illuminate\Support\Collection' does not have a method 'comments'
I think you would need to loop thru the collection as the relationship links()
is actually bound to the model, not collection. So maybe try like (?)
Untested code tho :D
$posts->comments->each(function($comment)
{
$comment->links();
});
$comment->links() gives this error:
ErrorException
Call to undefined method Illuminate\Database\Query\Builder::links()
Ah I actually misread the post.
If you look at the API, links()
actually belongs to class Paginator
http://laravel.com/api/class-Illuminate.Pagination.Paginator.html
You did a paginate()
to Post so therefore,
$posts->links() should work.
If you would like to obtain links for comments, you will probably need to do one more paginate on comments. Something like
$posts->each(function($post)
{
// Grab comments for this post
$post->comments()->paginate(10)->links();
});
You can't do that with eager loading.
In fact you have not succeeded to paginate the comments, you only limited loaded comments to 5 (total not per post). Moreover this code runs 2 queries on the comments table, one when you use paginate
method on the comments (it's ignored in the end), and second, similar, when Eloquent finally fetches related models.
So basically if you want to paginate related comments, you need to do this for each post separately.
Agree.
fatihtir, you should consider rewriting your query. Something just pops up from my head, to avoid doing paginate() on each post and stick with the "eager loading" way, maybe you should consider doing a Paginator manually while looping your posts?
-Untested code- :D
// You could definitely "limit" your comments here, just being lazy to write it out. :D
$posts = Post::with('comments')->paginate(10);
$posts->each(function($post)
{
$comments = $post->comments;
// Create a new Paginator instance.
$paginator = Paginator::make($comments->toArray(), $comments->count(), 5);
echo $paginator->links();
});
Something similar to this?
PS: If you check how many queries are executed by running
echo '<pre>'; var_dump(DB::getQueryLog()); echo '</pre>';
at the end, you should see only 2 queries executed.
jarektkaczyk said:
You can't do that with eager loading.
In fact you have not succeeded to paginate the comments, you only limited loaded comments to 5 (total not per post). Moreover this code runs 2 queries on the comments table, one when you use
paginate
method on the comments (it's ignored in the end), and second, similar, when Eloquent finally fetches related models.So basically if you want to paginate related comments, you need to do this for each post separately.
Sign in to participate in this thread!
The Laravel portal for problem solving, knowledge sharing and community building.
The community