Support the ongoing development of Laravel.io →
Database Eloquent
Last updated 2 years ago.
0

Greetings, if you already has a results grabbed from the DB, you could use sortBy() on collection

http://laravel.com/docs/eloquent#collections

Last updated 2 years ago.
0

delmadord said:

Greetings, if you already has a results grabbed from the DB, you could use sortBy() on collection

http://laravel.com/docs/eloquent#collections

Thank you for the reply. I am still stumped on how to get the account of the favourites in that spot thought. So if I do a collection sort as follows:

$posts = $posts->sortBy(favourites->count);

How so I tell it to sort by that?

Last updated 2 years ago.
0

I would be interested in eloquent solution to this too. SortBy on Eloquent collection is possible, but is sorting on application level, which is not very efficient.

Only way I know about right now, is writing the query using fluent and do the sorting on database level.

Last updated 2 years ago.
0

Here ya go

Just add this to the query chain:

->selectRaw('*, (SELECT COUNT(*) FROM favourites WHERE favourites.post_id = posts.id) favourites_count')->
Last updated 2 years ago.
0

Sign in to participate in this thread!

Eventy

Your banner here too?

stueynet stueynet Joined 21 May 2014

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.