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 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器