【问题标题】:Laravel whereHas eloqvent relationLaravel where 有 eloqvent 关系
【发布时间】:2016-11-30 08:44:20
【问题描述】:

我正在尝试从表 order_status_history 中获取具有相关属性的表 order 对象。从表 order_status_history 中,我只需要状态为“正在查看”的最后一条记录,因此我使用按字段 created_at 排序的 asc。到目前为止我的代码是,但我得到错误。

$orders = Order::GetOrderHistoryReviewing()->get();

 public function scopeGetOrderHistoryReviewing($query)
    {
        return $query->whereHas('statusHistory', function($q) {

           $q->where('status', 'Reviewing')->orderBy('created_at','desc')->first();

        });
    }

我需要一个与第二张表有关系的对象

这是我的错误

[2016-07-27 08:37:26] dev.ERROR: exception 'PDOException' with message 'SQLSTATE[42P01]: Undefined table: 7 ERROR:  missing FROM-clause entry for table "orders"
LINE 1: ...ries" where "order_status_histories"."order_id" = "orders"."...

【问题讨论】:

  • 那么你的问题是什么?您提到了一个错误,但我在您的帖子中没有看到任何错误。如果您需要帮助,您需要提供更多信息、您遇到的错误中的文本、您迄今为止尝试修复它的方法等。
  • 我认为第一个不工作我得到查询错误
  • 太好了,您还没有告诉我们错误。复制错误给出的确切字词并用它们更新您的问题...
  • 这是我的错误 [2016-07-27 08:37:26] dev.ERROR: exception 'PDOException' with message 'SQLSTATE[42P01]: Undefined table: 7 ERROR: missing FROM-clause表“订单”第 1 行的条目:...ries" where "order_status_histories"."order_id" = "orders"."...
  • 只需删除first() 调用。这用于实际运行查询,但范围用于过滤来自数据库查询的结果。

标签: php laravel


【解决方案1】:

根据您的问题,您显然是在尝试创建一个范围,以返回状态为“正在审查”的订单并按降序对结果进行排序。

您需要从$q 子查询中删除first() 调用,并将orderBy 移动到$query 的末尾。你的代码应该是这样的。

public function scopeGetOrderHistoryReviewing($query)
{
    return $query->whereHas('statusHistory', function($q) {

       $q->where('status', 'Reviewing');

    })->orderBy('created_at','desc');
}

那么你可以这样做:

$orders = Order::GetOrderHistoryReviewing()->get();
//OR to get the first record
$first_order = Order::GetOrderHistoryReviewing()->first();

【讨论】:

  • 但我需要从 statusHistory order by desc 而不是 table Orders 中的第一条记录
  • 那么你可以使用orderBy('statusHistory.created_at', 'desc') :)
  • 但我不会得到第一条记录
猜你喜欢
  • 2021-02-10
  • 2019-11-24
  • 2022-01-21
  • 1970-01-01
  • 1970-01-01
  • 2018-05-17
  • 2016-09-08
  • 2021-08-24
  • 2014-06-12
相关资源
最近更新 更多