Support the ongoing development of Laravel.io →
Eloquent
Last updated 1 year ago.
0

Try

$posts = \App\Post::orderBy('viewsCount')->get();

or

$posts = \App\Post::all()->sortBy('viewsCount');

When you use Post::*** you're accessing a query builder object, but when you call something like all() or get(), you're accessing the Eloquent result object. For some reason the ordering function is called sortBy in the result object. I wonder if it's because it actually performs a sort on the array. Not sure...

Last updated 8 years ago.
0

That's because sortBy() uses PHP to sort the data. You are basically getting the entire database, looping through it, and sorting it by using PHP. It's "better" to let MySQL handle the sorting because it's optimized to handle tasks like this.

For this, we would need to use joins, but unfortunately, we weren't told exactly how the relationship is setup, or the table names, fields, etc. Something like this should work, but you would need to adjust it according to how you have your database setup.

$posts = Post::select(DB::raw('posts.*, count(*) as `aggregate`'))
    ->join('views', 'posts.id', '=', 'views.post_id')
    ->groupBy('post_id')
    ->orderBy('aggregate', 'desc')
    ->get();
0

Ah yes, sorry OP, I didn't read your question correctly. Thanks for the clarification Thomastkim.

0

Thomastkim, it is perfect answer. thanks

I just want one more help. I have to use paginate in this result?

0

caioregatieri said:

Thomastkim, it is perfect answer. thanks

I just want one more help. I have to use paginate in this result?

Already got. excuse the annoying.

0

Sign in to participate in this thread!

Eventy

Your banner here too?

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2024 Laravel.io - All rights reserved.