Friday 15 August 2014

Laravel sortBy paginate -



Laravel sortBy paginate -

i have posts table , comments table, comment belongs post, , have relationship setup in post , comment model. did sort posts number of comments of each post this:

$posts = post::with('comments')->get()->sortby(function($post) { homecoming $post->comments->count(); });

what wonder how can paginate these sorted posts?

$posts = post::with('comments')->get()->sortby(function($post) { homecoming $post->comments->count(); })->paginate(20);

doesn't work , gives me error says paginate undefined method.

i don't know if can using eloquent can utilize bring together this:

$posts = post::leftjoin('comments','posts.id','=','comments.post_id')-> selectraw('posts.*, count(comments.post_id) `count`')-> groupby('posts.id')-> orderby('count','desc')-> paginate(20);

however seems in case records taken database , displayed paginator, if have many records it's waste of resources. seems should manual pagination this:

$posts = post::leftjoin('comments','posts.id','=','comments.post_id')-> selectraw('posts.*, count(comments.post_id) `count`')-> groupby('posts.id')-> orderby('count','desc')-> skip(0)->take(20)->get();

using skip , take i'm not eloquent expert , maybe there's improve solution accomplish goal can wait , maybe give improve answer.

laravel laravel-4 eloquent paginate laravel-paginate

No comments:

Post a Comment