Custom sorting on a laravel relationship collection

后端 未结 2 1009
旧巷少年郎
旧巷少年郎 2021-02-14 04:11

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 \

2条回答
  •  傲寒
    傲寒 (楼主)
    2021-02-14 04:36

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

提交回复
热议问题