問題描述
我知道在使用查詢構建器時,可以使用
I know that when using the query builder, it is possible to sort by multiple columns using
...orderBy('column1')->orderBy('column2')
但現在我正在處理一個 collection 對象.集合具有 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)
但這顯然只是按順序應用排序,最終按 column2 排序,而忽略 column1.我試過了
but this apparently just applies the sorts sequentially and it ends up sorted by column2, disregarding column1. I tried
sortBy('column1', 'column2')
但這會引發錯誤asort() 期望參數 2 很長,給出的字符串".使用
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 集合進行排序的語法是什么?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!