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.
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.
Sign in to participate in this thread!
The Laravel portal for problem solving, knowledge sharing and community building.
The community