Laravel 关系集合的自定义排序
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31983216/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Custom sorting on a laravel relationship collection
提问by Josh Undefined
I'm a little stuck on something that usually is quite straight forward. I need to sort records from a hasMany relationship into a custom order based on a certain value and an 'sort order' array.
我有点坚持一些通常很简单的事情。我需要根据某个值和“排序顺序”数组将 hasMany 关系中的记录排序为自定义顺序。
My code below doesn't work because I'm passing uSort() a eloquent collection and I'm not sure how to get around it.
我下面的代码不起作用,因为我向 uSort() 传递了一个雄辩的集合,但我不知道如何解决它。
$go = $this->hasMany('Product')->orderBy('colour','DESC');
$order = array('RED', 'GREEN', 'BLUE', 'YELLOW');
usort($go, function ($a, $b) use ($order) {
$pos_a = array_search($a->colour, $order);
$pos_b = array_search($b->colour, $order);
return $pos_a - $pos_b;
});
return $go;
Maybe I'm missing some amazing laravel magic helper, but I'm stuck. Any thoughts or advice would be much appreciated!
也许我错过了一些神奇的 Laravel 魔法助手,但我被卡住了。任何想法或建议将不胜感激!
Cheers
干杯
回答by jedrzej.kurylo
The usortequivalent for Collectionis the sort()method. It takes a callback as a parameter and returns the sorted collection.
Collection的usor等价物是sort()方法。它接受一个回调作为参数并返回排序后的集合。
So in your case, the solution is:
所以在你的情况下,解决方案是:
$go = $go->sort(function ($a, $b) use ($order) {
$pos_a = array_search($a->colour, $order);
$pos_b = array_search($b->colour, $order);
return $pos_a - $pos_b;
});
回答by ARIF MAHMUD RANA
Your sorting will be applied only after you get the result while here $go = $this->hasMany('Product')->orderBy('colour','DESC');
you are just getting an instance of a class which will return can return your result if you apply a get
method on it.
只有在您获得结果后才会应用您的排序,而在这里$go = $this->hasMany('Product')->orderBy('colour','DESC');
您只是获得一个类的实例,如果您对其应用get
方法,它将返回可以返回您的结果。
For your purpose you have to use sortBy method
of laravel collections
after you get the result of your data you can find more (laravel Collection sortBy() method)& here is a similar question answer for you https://stackoverflow.com/a/28202985
为了您的目的,您必须在获得数据结果后使用sortBy method
,laravel collections
您可以找到更多(laravel Collection sortBy() 方法)&这里有一个类似的问题答案https://stackoverflow.com/a/28202985