php - Laravel: Eloquent orderBy hasOne 关系列使用 with

标签 php laravel laravel-5 laravel-5.7

我有一个模型 OrdershasOne 关系 participant

public function participant()
{
    return $this->hasOne('App\OrderParticipant', 'order_id');
}

我需要检索按 participant.last_name 排序的 Orders 集合

我的做法

$orders = \App\Orders::with(['participant',])
              ->where('user_id', $user->id)  
              ->orderBy('participant.last_name')
              ->get();

失败:

Undefined table: 7 ERROR: missing FROM-clause entry for table \"participant\"\nLINE 1: ...1

我试过收集后整理

return $orders->sortBy('participant.last_name');

但这根本不排序

顺便说一句,我正在使用 postgres

谢谢。

最佳答案

不能直接用hasOne下单,必须用join

$orders = \App\Orders::with([
                'participant',                    
                ])
            ->where('orders.user_id', $user->id)  
            ->join('participants', 'orders.user_id', '=', 'participants.id')
            ->orderBy('participants.last_name')
            ->select('orders.*','participants.id','participants.last_name')
            ->get();


关于php - Laravel: Eloquent orderBy hasOne 关系列使用 with,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55841380/

相关文章:

php - Laravel 请求仅在更改时更新唯一字段

php - Laravel 在 hasManyThrough 中包含用户的帖子

Laravel 5.4 通过异步队列保存模型

php - 从输入表单到C源代码,检查不允许的关键字

php - 对列 C、D 进行分组/求和的 SQL 查询,当 A、B 相等时

php - Laravel 属于类关系

laravel - Created_at 保存时区错误

laravel - vue-loader 15 与 laravel-mix

php - 如何将带有 webservice 的产品从 xml 文件添加到 prestashop

php - 使用 Guzzle 删除带有参数的请求