Laravel/Eloquent - 在不使用表名的情况下按模型的关系排序

Ada*_*ell 2 php postgresql eloquent laravel-4

我有一个Person雄辩的模型,belongsTo一个Address.我的Laravel版本是4.2.5,我正在使用PostgreSQL.

class Person extends Eloquent {
    public function address() {
        return $this->belongsTo('Address');
    }
}
Run Code Online (Sandbox Code Playgroud)

我的目标是获取Person按相关Address模型的address_1字段排序的资源集合.

我可以通过引用如下所示的表名来实现这一点,但我想用Eloquent关系来代替它,因为我不想为了抽象目的而处理表.

Person::join('addresses', 'persons.id', '=', 'addresses.person_id')
    ->orderBy('address_1', 'asc')->get();
Run Code Online (Sandbox Code Playgroud)

我尝试了以下Eloquent方法但没有成功.

Person::with('address')->whereHas('address', function($q)
    {
        $q->orderBy('address_1', 'asc');
    })->get();
Run Code Online (Sandbox Code Playgroud)

此查询失败,并显示错误消息:

Grouping error: 7 ERROR:  column \"addresses.address_1\" must appear in the 
GROUP BY clause or be used in an aggregate function
Run Code Online (Sandbox Code Playgroud)

为此,我尝试在orderBy语句上方添加此行,这会导致查询成功,但排序对生成的Person集合没有影响.

$q->groupBy('address_1');
Run Code Online (Sandbox Code Playgroud)

我非常感谢一个解决方案,如果可能的话,我不必引用表名.我已经用尽了这个主题的所有资源,但这肯定是一个常见的用例.

Jar*_*zyk 5

干得好:

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

$results = $person->join(

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

)->orderBy($table.'.address_1', 'asc')
 ->get();
Run Code Online (Sandbox Code Playgroud)