Sorting a many to many relation with Laravel Eloquent

余生颓废 提交于 2019-12-25 04:43:33

问题


I do have swatches table, a colors table and a swatch_color pivot table.

Relations are set as:

public function colors()
{
    return $this->belongsToMany('Color');
}

public function swatches()
{
    return $this->belongsToMany('Swatch');
}

I have no problem to retrieve the swatches with the color relations

$swatches = Swatch::with('colors')->get();
return dd($swatches);

Colors is always an array of 5 color objects with hue, R, G, and B attributes.

Now I would like to sort the swatches by the R value of the first related color.


回答1:


This is all you need to sort $swatches collection:

$swatches->sortBy(function ($swatch) {
  return ($color = $swatch->colors->first())
     ? $color->r
     : null;
});

Another way would be manual joining the tables.

You can use sortByDesc for descending order.




回答2:


Best Solution

$collection = collect($arr);
     $sorted = $collection->sortBy(function($vv, $kk) {
           return [$vv['isFriend'],$vv['isCoworker'],$vv['icecount']];
            });

 $finalArr = $sorted->values()->all();


来源:https://stackoverflow.com/questions/28186823/sorting-a-many-to-many-relation-with-laravel-eloquent

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