Laravel查询构建器-修改了where语句的重用查询 [英] Laravel query builder - re-use query with amended where statement

查看:41
本文介绍了Laravel查询构建器-修改了where语句的重用查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的应用程序动态地构建并运行复杂的查询以生成报告.在某些情况下,我需要获取多个(有些任意的)日期范围,而所有其他参数都相同.

My application dynamically builds and runs complex queries to generate reports. In some instances I need to get multiple, somewhat arbitrary date ranges, with all other parameters the same.

因此,我的代码使用一堆联接,位置,排序,限制等来构建查询,然后运行查询.然后,我想做的是跳入Builder对象并更改where子句,该子句定义了要查询的日期范围.

So my code builds the query with a bunch of joins, wheres, sorts, limits etc and then runs the query. What I then want to do is jump into the Builder object and change the where clauses which define the date range to be queried.

到目前为止,我已经做到了,以便在任何其他wheres之前设置日期范围,然后尝试手动更改wheres数组的相关属性中的值.像这样;

So far, I have made it so that the date range is setup before any other wheres and then tried to manually change the value in the relevant 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 (having already done it once already)

$this->data_qry->get();

虽然不起作用.该查询仅在原始日期范围内运行.即使我的方法行得通,但我仍然不喜欢它,因为它似乎不稳定地依赖(某种耦合?).IE;如果没有首先设置日期,那么一切都将分崩离析.

Doesn't work though. The query just runs with the original date range. Even if my way worked, I still wouldn't like it though as it seems to be shot through with a precarious dependence (some sort of coupling?). Ie; if the date wheres aren't set up first then it all falls apart.

可以从头开始重新设置整个查询,只是使用不同的日期范围,但这似乎很有意义,因为查询中的所有其他内容都必须与上一次使用时相同.

I could set the whole query up again from scratch, just with a different date range, but that seems ott as everything else in the query needs to be the same as the previous time it was used.

任何关于如何以正确/最简洁的方式实现此目标的想法都非常受欢迎.

Any ideas for how to achieve this in the correct / neatest way are very welcome.

谢谢

杰夫

推荐答案

您可以使用 clone 复制查询,然后使用其他where语句运行该查询.首先,构建没有从头到尾约束的查询,然后执行以下操作:

You can use clone to duplicate the query and then run it with different where statements. First, build the query without the from-to constraints, then do something like this:

$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();

这篇关于Laravel查询构建器-修改了where语句的重用查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆