想要在查询中生成多个结果。
$now = Carbon::now();
$currentStartDay = $now->startOfDay();
$currentEndDay = $now->endOfDay();
$currentStartWeek = $now->startOfWeek();
$currentEndWeek = $now->endOfWeek();
$currentStartMonth = $now->startOfMonth();
$currentEndMonth = $now->endOfMonth();
$currentStartYear = $now->startOfYear();
$currentEndYear = $now->endOfYear();
$query = DB::table('transactions AS t');
$queryExpenseToday = $query;
$queryExpenseWeek = $query;
$queryExpenseMonth = $query;
$queryExpenseYear = $query;
dump($queryExpenseToday->whereBetween('t.created_at', [$currentStartDay, $currentEndDay])->toSql());
dump($queryExpenseWeek->whereBetween('t.created_at', [$currentStartWeek, $currentEndWeek])->toSql());
dump($queryExpenseMonth->whereBetween('t.created_at', [$currentStartMonth, $currentEndMonth])->toSql());
dump($queryExpenseYear->whereBetween('t.created_at', [$currentStartYear, $currentEndYear])->toSql());
问题和输出如下:
第一次转储
"select * from `transactions` as `t` where `t`.`created_at` between ? and ?"
第二次转储
"select * from `transactions` as `t` where `t`.`created_at` between ? and ? and `t`.`created_at` between ? and ?"
第三次转储
"select * from `transactions` as `t` where `t`.`created_at` between ? and ? and `t`.`created_at` between ? and ? and `t`.`created_at` between ? and ?"
第四个转储
"select * from `transactions` as `t` where `t`.`created_at` between ? and ? and `t`.`created_at` between ? and ? and `t`.`created_at` between ? and ? and `t`.`created_at` between ? and ?"
正在附加查询,如何停止此查询? 或如何取消绑定最后一个绑定参数?
我正在使用Laravel 5.6
寻找最佳答案。
答案 0 :(得分:1)
关于重新执行查询该怎么办?代替:
...
$query = DB::table('transactions AS t');
$queryExpenseToday = $query;
$queryExpenseWeek = $query;
...
您可以这样做:
...
$query = DB::table('transactions AS t');
$queryExpenseToday = DB::table('transactions AS t');
$queryExpenseWeek = DB::table('transactions AS t');
...
或者您也可以克隆它:
...
$query = DB::table('transactions AS t');
$queryExpenseToday = clone($query);
$queryExpenseWeek = clone($query);
...
解释很简单。使用DB时,它会在内部创建一个Object的新实例,因此,如果使用$anyQuery=$query
,则将引用引用到同一个第一个Object。因此,您必须创建一个新的(第一个选项)或克隆它,然后在内部创建一个新的(第二个选项)
您可以使用dd($anyQuery)
进行检查,并在概念上稍作改动。
好看!
答案 1 :(得分:1)
认为您正在此处处理对象,因此实际上您正在处理相同的实例。
因此,通常情况下,您可以设置通用查询代码,就您而言:
// https://mvnrepository.com/artifact/com.cloudinary/cloudinary-http43
compile group: 'com.cloudinary', name: 'cloudinary-http43', version: '1.2.2'
但是如果您想为其添加不同的条件并有多个查询,则需要克隆,而不是:
$query = DB::table('transactions AS t');
您应该使用:
$queryExpenseToday = $query;
$queryExpenseWeek = $query;
$queryExpenseMonth = $query;
$queryExpenseYear = $query;
当然,您可以在一行中完成此操作,因此也可以像这样转储它(并在确保其确实起作用后将其分配给变量):
$queryExpenseToday = clone $query;
$queryExpenseWeek = clone $query;
$queryExpenseMonth = clone $query;
$queryExpenseYear = clone $query;