Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the syntax for sorting an Eloquent collection by multiple columns?

I know that when using the query builder, it is possible to sort by multiple columns using

...orderBy('column1')->orderBy('column2') 

but now I am dealing with a collection object. Collections have the sortBy method, but I have not been able to figure out how to make it work for multiple columns. Intuitively, I initially tried to use the same syntax as orderBy.

sortBy('column1')->sortBy('column2) 

but this apparently just applies the sorts sequentially and it ends up sorted by column2, disregarding column1. I tried

sortBy('column1', 'column2') 

but that throws the error "asort() expects parameter 2 to be long, string given". Using

sortBy('column1, column2') 

doesn't throw an error, but the sort appears to be pretty random, so I don't really know what that actually does. I looked at the code for the sortBy method, but unfortunately I am having a hard time understanding how it works.

like image 885
Don't Panic Avatar asked Aug 22 '14 15:08

Don't Panic


People also ask

What is multiple column sorting?

To sort by multiple columns, simply specify the column names separated by commas (just as you do when you are selecting multiple columns). The following code retrieves three columns and sorts the results by two of them—first by price and then by name.

How do you use order by in eloquent?

To sort results in the database query, you'll need to use the orderBy() method, and provide the table field you want to use as criteria for ordering. This will give you more flexibility to build a query that will obtain only the results you need from the database. You'll now change the code in your routes/web.


1 Answers

sortBy() takes a closure, allowing you to provide a single value that should be used for sorting comparisons, but you can make it a composite by concatenating several properties together

$posts = $posts->sortBy(function($post) {     return sprintf('%-12s%s', $post->column1, $post->column2); }); 

If you need the sortBy against multiple columns, you probably need to space pad them to ensure that "ABC" and "DEF" comes after "AB" and "DEF", hence the sprint right padded for each column up to the column's length (at least for all but the last column)

Note that it's generally a lot more efficient if you can use an orderBy in your query so the collection is ready-sorted on retrieval from the database

like image 97
Mark Baker Avatar answered Oct 06 '22 00:10

Mark Baker