简体   繁体   English

Laravel / Eloquent-按模型的关系排序而不使用表名

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

I have a Person eloquent model that belongsTo an Address . 我有一个Person雄辩的模型belongsTo一个Address My Laravel version is 4.2.5 and I am using PostgreSQL. 我的Laravel版本是4.2.5,我正在使用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. 我的目的是获得Person资源的集合,这些资源按其相关Address模型的address_1字段排序。

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. 响应于此,我尝试在orderBy语句上方添加此行,从而使查询成功,但是排序对结果Person集合没有影响。

$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();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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