laravel关系集合上的自定义排序 [英] Custom sorting on a laravel relationship collection
问题描述
我有点坚持通常很简单的方法.我需要根据特定值和排序顺序"数组将hasMany关系中的记录排序为自定义顺序.
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.
下面的代码无法正常工作,因为我正在向雄辩的集合传递uSort(),并且不确定如何解决它.
My code below doesn't work because I'm passing uSort() a eloquent collection and I'm not sure how to get around it.
$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;
也许我缺少一些出色的Laravel魔术助手,但我被困住了.任何想法或建议将不胜感激!
Maybe I'm missing some amazing laravel magic helper, but I'm stuck. Any thoughts or advice would be much appreciated!
欢呼
推荐答案
与 Collection 等效的 usort 是 sort()方法.它以回调为参数,并返回已排序的集合.
The usort equivalent for Collection is the sort() method. It takes a callback as a parameter and returns the sorted collection.
因此,在您的情况下,解决方案是:
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;
});
这篇关于laravel关系集合上的自定义排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!