与Laravel Eloquent进行多对多排序 [英] Sorting a many to many relation with Laravel Eloquent
本文介绍了与Laravel Eloquent进行多对多排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有色板表,颜色表和swatch_color数据透视表.
I do have swatches table, a colors table and a swatch_color pivot table.
关系设置为:
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);
颜色始终是由5个具有hue,R,G和B属性的颜色对象组成的数组.
Colors is always an array of 5 color objects with hue, R, G, and B attributes.
现在,我想按第一种相关颜色的R值对色板进行排序.
Now I would like to sort the swatches by the R value of the first related color.
推荐答案
这是对$swatches
集合进行排序所需的全部内容:
This is all you need to sort $swatches
collection:
$swatches->sortBy(function ($swatch) {
return ($color = $swatch->colors->first())
? $color->r
: null;
});
另一种方法是手动joining
表格.
Another way would be manual joining
the tables.
您可以使用sortByDesc
降序.
这篇关于与Laravel Eloquent进行多对多排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文