在Laravel 5中,Eloquent sortBy稳定吗?

时间:2015-06-01 12:36:06

标签: php eloquent laravel-5

Laravel 5 Eloquent集合的排序功能是否稳定?稳定的排序不会使用相同的排序键重新排序元素。

即,给定此输入列表:

| order | value |
|-------+-------|
| 5     | a     |
| 2     | b     |
| 5     | c     |
| 10    | d     |

我可以期望$list->sortBy('order')始终返回以下结果吗?

| order | value |
|-------+-------|
| 2     | b     |
| 5     | a     | <-- a and c have not
| 5     | c     | <-- switched places
| 10    | d     |

1 个答案:

答案 0 :(得分:3)

源代码可以在Illuminate/Support/Collection.php

中找到
public function sortBy($callback, $options = SORT_REGULAR, $descending = false)
{
    $results = [];
    if ( ! $this->useAsCallable($callback))
    {
        $callback = $this->valueRetriever($callback);
    }
    // First we will loop through the items and get the comparator from a callback
    // function which we were given. Then, we will sort the returned values and
    // and grab the corresponding values for the sorted keys from this array.
    foreach ($this->items as $key => $value)
    {
        $results[$key] = $callback($value, $key);
    }
    $descending ? arsort($results, $options)
                : asort($results, $options);
    // Once we have sorted all of the keys in the array, we will loop through them
    // and grab the corresponding model so we can set the underlying items list
    // to the sorted version. Then we'll just return the collection instance.
    foreach (array_keys($results) as $key)
    {
        $results[$key] = $this->items[$key];
    }
    $this->items = $results;
    return $this;
}

sort() family isn't stable以来,此功能也不稳定。

stable PHP sort functions,但如果您想使用它们,则需要修补Laravel。