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.
Best Solution
This is all you need to sort
$swatches
collection:Another way would be manual
joining
the tables.You can use
sortByDesc
for descending order.