Laravel查询构建器 - 使用修改的where语句重用查询

Geo*_*ton 25 php mysql query-builder laravel

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

所以我的代码使用一堆连接,数组,排序,限制等来构建查询,然后运行查询.我当时想要做的是跳转到Builder对象并更改where子句,这些子句定义要查询的日期范围.

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

$this->data_qry->wheres[0]['value'] = $new_from_date;
$this->data_qry->wheres[1]['value'] = $new_to_date;
Run Code Online (Sandbox Code Playgroud)

然后我做(已经做过一次)

$this->data_qry->get();
Run Code Online (Sandbox Code Playgroud)

虽然不起作用.查询只与原始日期范围一起运行.即使我的方式有效,我仍然不喜欢它,因为它似乎是以不稳定的依赖(某种耦合?)来拍摄的.即; 如果没有先设置日期,则它们全部崩溃.

可以从头开始重新设置整个查询,只是使用不同的日期范围,但这看起来很糟糕,因为查询中的其他内容需要与上次使用时相同.

如何以正确/最好的方式实现这一点的任何想法都是非常受欢迎的.

谢谢,

杰夫

luk*_*ter 57

您可以使用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();
Run Code Online (Sandbox Code Playgroud)

  • 非常感谢你,我已经被困在这个问题上几个小时了,我想你可以通过执行 $query2 = $query1; 来克隆查询。 (3认同)

Lar*_*ole 15

对于想要更简单、更短语法的人,您可以clone()在查询生成器上以菊花链方式连接该方法。

$result1 = $this->data_qry->clone()->where('from', $from1)->where('to', $to1)->get();
$result2 = $this->data_qry->clone()->where('from', $from2)->where('to', $to2)->get();
Run Code Online (Sandbox Code Playgroud)


小智 6

@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();
Run Code Online (Sandbox Code Playgroud)

  • 或者将克隆语句括在括号中:`(clone $ this-> data_qry)-> where('from',$ from1);` (14认同)