douan2478 2014-08-17 05:58
浏览 155
已采纳

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

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.

  • 写回答

1条回答 默认 最新

  • dongmouhao7438 2014-08-17 08:54
    关注

    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();
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部