douan2478 2014-08-17 13: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 16: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();
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化
  • ¥15 Mirare PLUS 进行密钥认证?(详解)
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥20 想用ollama做一个自己的AI数据库
  • ¥15 关于qualoth编辑及缝合服装领子的问题解决方案探寻
  • ¥15 请问怎么才能复现这样的图呀