Laravel query builder - reusing a query with a modified where clause

My application dynamically builds and runs complex queries to create reports. In some cases, I need to get several, several arbitrary date ranges, and all other parameters are the same.

So, my code builds the request with a bunch of unions, wheres, sorts, limits, etc., and then runs the request. What I then want to do is go to the Builder object and change the where clauses that define the date range for the query.

So far, I have done this so that the date range is set before any other users, and then tried to manually change the value in the corresponding attribute of the wheres array. Like this:

$this->data_qry->wheres[0]['value'] = $new_from_date;
$this->data_qry->wheres[1]['value'] = $new_to_date;

Then I do (already done it once already)

$this->data_qry->get();

Does not work. The query only runs with the original date range. Even if my method worked, I still would not like it, although it seems to be broken through with an unstable dependence (some kind of connection?). Those.; if the date is not set first, then it all falls apart.

I could ask the whole query again from scratch, with only a different date range, but that seems ott, since everything else in the request should be the same as in the previous time when it was used.

Any ideas on how to achieve this in a proper / neat way are very welcome.

Thank,

Jeff

+4
source share
2 answers

clone , where. -, from-to, - :

$query1 = $this->data_qry;
$query2 = clone $query1;

$result1 = $query1->where('from', $from1)->where('to', $to1)->get();
$result2 = $query2->where('from', $from2)->where('to', $to2)->get();
+19

@lukasgeiter, , , ; , Eloquent\Builder Query\Builder, .

, Laravel with(), , :

$result1 = with(clone $this->data_qry)->where('from', $from1)->where('to', $to1)->get();
$result2 = with(clone $this->data_qry)->where('from', $from2)->where('to', $to2)->get();
+1

All Articles