laravel关系集合上的自定义排序 [英] Custom sorting on a laravel relationship collection

查看:656
本文介绍了laravel关系集合上的自定义排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有点坚持通常很简单的方法.我需要根据特定值和排序顺序"数组将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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆