繁体   English   中英

查询Laravel中with()关系的结果

[英]Query the results from with() relationship in Laravel

所以我有一个with()关系,每个客户都分配了订单。 我尝试仅在一定时期内退回订单,如下所示:

if (isset($filters["date_from"]) && strlen($filters["date_from"]) > 0) {
     $value = date('Y-m-d', strtotime($filters["date_from"]));
     $sales_by_customer = $sales_by_customer->with(array("orders" => function ($query) use ($value) {
          $query->whereDate("created_at", '>=', $value);
     }));
}

如您所见,我只想为每个客户退还一定时期内的订单。 但是现在,它并没有考虑我的查询,它只是返回每个客户的所有订单。 任何想法如何获得我想要的。 谢谢大家的时间!

如果$sales_by_customer还不是集合with则用替换为load

if (isset($filters["date_from"]) && strlen($filters["date_from"]) > 0) {
     $value = date('Y-m-d', strtotime($filters["date_from"]));
     $sales_by_customer = $sales_by_customer->load(array("orders" => function ($query) use ($value) {
          $query->where("created_at", '>=', $value);
     }));
}

假设$sales_by_customer是单个客户, $sales_by_customer提取在特定时间之间创建的所有订单。

$sales_by_customer->orders->where("created_at", '>=', $value)->all();

如果$sales_by_customer是多个客户的集合,则需要在foreach循环内的where查询中运行。

foreach($sales_by_customer as $customerSale) {
   $customerSale->orders->where("created_at", '>=', $value)->all();
}

解决方案:显然问题是由于某种原因,我无法使用whereDate,并且不得不使用简单的where子句,但对格式进行了一些更改,但我却获得了日期(在DB created_at中,其格式如下: Ymd H:i:s和my过滤日期的格式为: Ymd ),因此解决方案如下所示:

if (isset($filters["date_from"]) && strlen($filters["date_from"]) > 0) {
     $value = date('Y-m-d 00:00:00', strtotime($filters["date_from"]));
     $sales_by_customer = $sales_by_customer->with(array("orders" => function ($query) use ($value) {
          $query->where("created_at", '>=', $value);
     }));
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM