按多列对Eloquent集合排序的语法是什么?


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

我知道在使用查询生成器时,可以使用

按多列排序
...orderBy('column1')->orderBy('column2')

,但现在我正在处理一个集合对象。集合有sortBy方法,但我还不能弄清楚如何使它为多列工作。直觉上,我最初尝试使用与orderBy相同的语法。

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

,但这显然只是按顺序应用排序,最终按column2排序,忽略了column1。我试着

sortBy('column1', 'column2')

,但会抛出错误"asort()期望参数2是长,字符串给定"。使用

sortBy('column1, column2')

不会抛出错误,但排序似乎是相当随机的,所以我真的不知道它实际上是做什么的。我查看了sortBy方法的代码,但不幸的是,我很难理解它是如何工作的。

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

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

如果您需要对多个列进行排序,您可能需要对它们进行空格填充,以确保"ABC"answers"DEF"出现在"AB"answers"DEF"之后,因此每个列的sprint右填充直到列的长度(至少对最后一列除外)

请注意,如果您可以在查询中使用orderBy,那么从数据库中检索集合时,集合已经就绪排序,通常会更有效率

我在雄辩的集合上使用sort()找到了一种不同的方法。它可能比填充字段工作得更好,或者至少更容易理解。这个有更多的比较,但我没有为每个项目做sprintf()

$items = $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);
    }
);

正如@derekaug所提到的,sort方法允许我们输入一个自定义闭包来对集合进行排序。但我认为他的解决方案是有点麻烦,写起来很麻烦,如果有这样的东西就好了:

$collection = collect([/* items */])
$sort = ["column1" => "asc", "column2" => "desc"];
$comparer = $makeComparer($sort);
$collection->sort($comparer);

实际上,这可以通过以下$makeComparer包装器轻松归档,以生成compare闭包:

$makeComparer = function($criteria) {
  $comparer = function ($first, $second) use ($criteria) {
    foreach ($criteria as $key => $orderType) {
      // normalize sort direction
      $orderType = strtolower($orderType);
      if ($first[$key] < $second[$key]) {
        return $orderType === "asc" ? -1 : 1;
      } else if ($first[$key] > $second[$key]) {
        return $orderType === "asc" ? 1 : -1;
      }
    }
    // all elements were equal
    return 0;
  };
  return $comparer;
};

$collection = collect([
  ["id" => 1, "name" => "Pascal", "age" => "15"],
  ["id" => 5, "name" => "Mark", "age" => "25"],
  ["id" => 3, "name" => "Hugo", "age" => "55"],
  ["id" => 2, "name" => "Angus", "age" => "25"]
]);
$criteria = ["age" => "desc", "id" => "desc"];
$comparer = $makeComparer($criteria);
$sorted = $collection->sort($comparer);
$actual = $sorted->values()->toArray();
/**
* [
*  ["id" => 5, "name" => "Hugo", "age" => "55"],
*  ["id" => 3, "name" => "Mark", "age" => "25"],
*  ["id" => 2, "name" => "Angus", "age" => "25"],
*  ["id" => 1, "name" => "Pascal", "age" => "15"],
* ];
*/
$criteria = ["age" => "desc", "id" => "asc"];
$comparer = $makeComparer($criteria);
$sorted = $collection->sort($comparer);
$actual = $sorted->values()->toArray();
/**
* [
*  ["id" => 5, "name" => "Hugo", "age" => "55"],
*  ["id" => 2, "name" => "Angus", "age" => "25"],
*  ["id" => 3, "name" => "Mark", "age" => "25"],
*  ["id" => 1, "name" => "Pascal", "age" => "15"],
* ];
*/
$criteria = ["id" => "asc"];
$comparer = $makeComparer($criteria);
$sorted = $collection->sort($comparer);
$actual = $sorted->values()->toArray();
/**
* [
*  ["id" => 1, "name" => "Pascal", "age" => "15"],
*  ["id" => 2, "name" => "Angus", "age" => "25"],
*  ["id" => 3, "name" => "Mark", "age" => "25"],
*  ["id" => 5, "name" => "Hugo", "age" => "55"],
* ];
*/

现在,既然我们在这里谈论的是Eloquent,那么你很有可能也在使用Laravel。因此,我们甚至可以将$makeComparer()闭包绑定到IOC并从那里解析它:

// app/Providers/AppServiceProvider.php 
// in Laravel 5.1
class AppServiceProvider extends ServiceProvider
{
    /**
     * ...
     */

    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        $this->app->bind("collection.multiSort", function ($app, $criteria){
                return function ($first, $second) use ($criteria) {
                    foreach ($criteria as $key => $orderType) {
                        // normalize sort direction
                        $orderType = strtolower($orderType);
                        if ($first[$key] < $second[$key]) {
                            return $orderType === "asc" ? -1 : 1;
                        } else if ($first[$key] > $second[$key]) {
                            return $orderType === "asc" ? 1 : -1;
                        }
                    }
                    // all elements were equal
                    return 0;
                };
        });
    }
}

现在你可以在任何你需要的地方使用它:

$criteria = ["id" => "asc"];
$comparer = $this->app->make("collection.multiSort",$criteria);
$sorted = $collection->sort($comparer);
$actual = $sorted->values()->toArray();

一个简单的解决方案是将sortBy()按与排序顺序相反的顺序链接多次。缺点是这可能比在同一个回调中一次排序要慢,所以在大型集合中使用该方法风险自负。

$collection->sortBy('column3')->sortBy('column2')->sortBy('column1');