Support the ongoing development of Laravel.io →
Database Eloquent
Last updated 2 years ago.
0
Solution

Eloquent follows "Active Record" patter instead of "Data Mapper". That means it wont add the required "joins" for you. You have to join the related table by yourself.

For better reusability you can define a scope

/**
 * Sort model by parameters given in the URL
 * i.e: ?sort=name&order=desc
 *
 * @param Illuminate\Database\Eloquent\Builder
 * @return Illuminate\Database\Eloquent\Builder
 */
public function scopeOrderByUrl($query)
{
	$column = Input::get('sort');
	$direction = (Input::get('order') == 'desc') ? 'desc' : 'asc';
	
	return $query
	->select('realestates.*') // Avoid 'ambiguous column name' for paginate() method
	->leftJoin('realestate_rents', 'realestates.id', '=', 'realestate_rents.realestate_id') // Include related table
	->orderBy('realestates.price', $direction); // First sort by price
	->orderBy('realestate_rents.price_per_day', $direction); // Finally sort by related column
}

I didn't test it, but you get the idea ;)

BTW, you should not be exposing your real database columns names. Instead use a map between exposed "orderBy" names and real database column names.

Last updated 2 years ago.
0

Hi, your code has saved me :)

// prevent direct user variables in query
$direction = (Input::get('order') == 'desc') ? 'desc' : 'asc';

$realestates = $realestates
	->leftJoin('realestate_rents', 'realestates.id', '=', 'realestate_rents.realestate_id')
	->orderBy('realestates.price', $direction)
	->orderBy('realestate_rents.price_per_day', $direction)
	->select('realestates.*');

I did not require a scope at this moment, but if I ever reuse this piece of code I will use a scope. Thank you again.

Last updated 2 years ago.
0

Sign in to participate in this thread!

Eventy

Your banner here too?

mabasic mabasic Joined 3 Feb 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.