简体   繁体   中英

Laravel/Eloquent - Order By a Model's Relationship Without Using Table Names

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.

Here you go:

$person = new Person;
$relation = $person->address();
$table = $relation->getRelated()->getTable();

$results = $person->join(

 $table, $relation->getQualifiedForeignKey(), '=', $relation->getQualifiedOtherKeyName()

)->orderBy($table.'.address_1', 'asc')
 ->get();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM