I have a Person
eloquent model that belongsTo
an Address
. My Laravel version is 4.2.5 and I am using PostgreSQL.
class Person extends Eloquent {
public function address() {
return $this->belongsTo('Address');
}
}
My aim is to get a collection of Person
resources that are sorted by the address_1 field of their related Address
model.
I can accomplish this by referencing table names as show below, but I want to do it instead with Eloquent relationships, since I do not want to deal with tables for abstraction purposes.
Person::join('addresses', 'persons.id', '=', 'addresses.person_id')
->orderBy('address_1', 'asc')->get();
I have attempted the following Eloquent method without success.
Person::with('address')->whereHas('address', function($q)
{
$q->orderBy('address_1', 'asc');
})->get();
This query fails with the error message:
Grouping error: 7 ERROR: column \"addresses.address_1\" must appear in the
GROUP BY clause or be used in an aggregate function
In response to this, I tried adding this line above the orderBy
statement which causes the query to succeed, but the ordering has no effect on the resulting Person
collection.
$q->groupBy('address_1');
I would much appreciate a solution where I do not have to reference table names if it is possible. I have exhausted all resources on this subject, but surely this is a common use case.