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

前端 未结 4 1953

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

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

4条回答
  •  情话喂你
    2020-12-01 05:36

    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

提交回复
热议问题