用多列对Eloquent集合进行排序的语法是什么? [英] What is the syntax for sorting an Eloquent collection by multiple columns?

查看:144
本文介绍了用多列对Eloquent集合进行排序的语法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道使用查询构建器时,可以使用

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

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

但现在我正在处理一个<一个href =http://laravel.com/docs/eloquent#collections>集合对象。集合具有 sortBy 方法,但是我无法弄清楚如何使其成为多列。直觉上,我最初尝试使用与 orderBy 相同的语法。

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)

但这显然只适用于顺序地,它最后按列2排序,忽略列1。我试过

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

sortBy('column1', 'column2')

但抛出错误asort()期望参数2为long,字符串给。使用

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

sortBy('column1, column2')

不会发出错误,但是排序看起来很随机,所以我真的不知道这是什么。我查看了 sortBy方法的代码,但不幸的是我是很难理解它的工作原理。

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.

推荐答案

sortBy()关闭,允许您提供一个值用于排序比较的单一值,但您可以通过将多个属性连接在一起使其成为复合。

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);
});

如果您需要对多列进行sortBy,则可能需要对其进行空格填补,以确保ABC 和DEF来自AB和DEF,因此每列的冲刺权限填充到列的长度(至少对于除最后一列之外的所有列)

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)

请注意,如果您可以在查询中使用orderBy,则通常会更有效率,以便从数据库检索时可以对该集合进行排序。

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

这篇关于用多列对Eloquent集合进行排序的语法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆