Support the ongoing development of Laravel.io →
posted 10 years ago
Eloquent
Last updated 2 years ago.
0
  1. You need 2 joins in order to sort by 'far' related table.
  2. You can load it as is and then sort the collection (obviously this one won't scale etc so don't)

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');
}
Last updated 2 years ago.
0

Wow, I didn't know you could do that. Thank you.

Last updated 2 years ago.
0

I wish I had found this earlier...

Last updated 2 years ago.
0

this package can handle this on more elegant way https://github.com/fico7489/laravel-eloquent-join

0

Sign in to participate in this thread!

Eventy

Your banner here too?

houdas houdas Joined 23 Jul 2014

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2024 Laravel.io - All rights reserved.