So, you could create a scope for this, to make it easier:
// Product model
public function scopeOrderByPrice($query, $order = 'asc')
{
$relation = $this->variants(); // asuuming variants is relation name
$related = $relation->getRelated();
$table = $related->getTable();
$foreignKey = $relation->getForeignKey();
$farRelation = $related->price(); // assuming price is relation name
$farTable = $farRelation->getRelated()->getTable();
$farForeignKey = $farRelation->getForeignKey();
$query->join($table, $foreignKey, '=', $this->getQualifiedKeyName())
->join($farTable, $farForeignKey, '=', $related->getQualifiedKeyName())
->orderBy($farTable.'.'.'price', $order) // assuming price is column name on prices table
->select($this->getTable().'.*') // assuming you want only Product properties
->groupBy($this->getQualifiedKeyName());
}
// then
$products = Product::orderByPrice()->take(10)->get();
//or
$products = Product::orderByPrice()->paginate(10);
Of course you could hard-code everything in that join if you like:
public function scopeOrderByPrice($query, $order = 'asc')
{
$query->join('variants', 'variants.product_id', '=', 'products.id')
->join('prices', 'prices.variant_id', '=', 'variants.id')
->orderBy('prices.price', $order)
->select('products.*')
->groupBy('products.id');
}
Wow, I didn't know you could do that. Thank you.
this package can handle this on more elegant way https://github.com/fico7489/laravel-eloquent-join
Sign in to participate in this thread!
The Laravel portal for problem solving, knowledge sharing and community building.
The community