Custom sorting on a laravel relationship collection

心不动则不痛 提交于 2020-06-10 03:44:30

问题


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.

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;

Maybe I'm missing some amazing laravel magic helper, but I'm stuck. Any thoughts or advice would be much appreciated!

Cheers


回答1:


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;
});



回答2:


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.

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



来源:https://stackoverflow.com/questions/31983216/custom-sorting-on-a-laravel-relationship-collection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!