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

前端 未结 4 1954

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:46

    I found a different way to do this using sort() on the eloquent Collection. It may potentially work a bit better or at least be a bit easier to understand than padding the fields. I'd be interested to see which performs better, as this one has more comparisons but i'm not doing the sprintf() for every item.

    $items->sort(
        function ($a, $b) {
            // sort by column1 first, then 2, and so on
            return strcmp($a->column1, $b->column1)
                ?: strcmp($a->column2, $b->column2)
                ?: strcmp($a->column3, $b->column3);
        }
    );
    

提交回复
热议问题