使用 Laravel Eloquent 对多对多关系进行排序
Sorting a many to many relation with Laravel Eloquent
我确实有色板 table、颜色 table 和 swatch_color 枢轴 table。
关系设置为:
public function colors()
{
return $this->belongsToMany('Color');
}
public function swatches()
{
return $this->belongsToMany('Swatch');
}
我检索具有颜色关系的色板没问题
$swatches = Swatch::with('colors')->get();
return dd($swatches);
Colors 始终是一个包含 5 个具有色调、R、G 和 B 属性的颜色对象的数组。
现在我想按第一个相关颜色的 R 值对样本进行排序。
这就是您需要对 $swatches
集合进行排序的全部内容:
$swatches->sortBy(function ($swatch) {
return ($color = $swatch->colors->first())
? $color->r
: null;
});
另一种方法是手动 joining
表格。
您可以使用 sortByDesc
进行降序排列。
最佳解决方案
$collection = collect($arr);
$sorted = $collection->sortBy(function($vv, $kk) {
return [$vv['isFriend'],$vv['isCoworker'],$vv['icecount']];
});
$finalArr = $sorted->values()->all();
我确实有色板 table、颜色 table 和 swatch_color 枢轴 table。
关系设置为:
public function colors()
{
return $this->belongsToMany('Color');
}
public function swatches()
{
return $this->belongsToMany('Swatch');
}
我检索具有颜色关系的色板没问题
$swatches = Swatch::with('colors')->get();
return dd($swatches);
Colors 始终是一个包含 5 个具有色调、R、G 和 B 属性的颜色对象的数组。
现在我想按第一个相关颜色的 R 值对样本进行排序。
这就是您需要对 $swatches
集合进行排序的全部内容:
$swatches->sortBy(function ($swatch) {
return ($color = $swatch->colors->first())
? $color->r
: null;
});
另一种方法是手动 joining
表格。
您可以使用 sortByDesc
进行降序排列。
最佳解决方案
$collection = collect($arr);
$sorted = $collection->sortBy(function($vv, $kk) {
return [$vv['isFriend'],$vv['isCoworker'],$vv['icecount']];
});
$finalArr = $sorted->values()->all();