简体   繁体   中英

Query the results from with() relationship in Laravel

So I have a with() relationship, each customer having assigned orders. I try to return the orders only for a certain period, like this:

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);
     }));
}

As you can see I want to return for each client only the orders from a certain period. But right now it doesn't take into account my query and it simply returns all orders for each client. Any idea how to obtain what I want. Thank you all for your time!

Replace load with with if $sales_by_customer isn't already a collection.

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);
     }));
}

Assuming $sales_by_customer is a single customer, to fetch all the order created between specific time.

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

If $sales_by_customer is a collection of multiple customers then you need to run where query inside a foreach loop.

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

Solution: Apparently the problem was that for some reason I cannot user whereDate and I had to use a simple where clause with some changes to the format I get the date (in DB created_at has the following format: Ymd H:i:s and my filter date had this format: Ymd ) So the solution looks like this:

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);
     }));
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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