我正试图从我的表格中获取本周的数据
我有以下代码,它给了我31天的数据(一个月,但它是分开的,这是我需要的)
$stats["tmv"] = "";
$stats["tmd"] = "";
$stats["tru"] = array();
for ($i=1; $i <= 31; $i++) {
$stats["tmv"] .= DB::table('stats')->select(DB::raw('*'))->where(DB::raw('DAY(created_at)'), '=', $i)->where('stats_type', "mv")->count();
$stats["tmd"] .= DB::table('stats')->select(DB::raw('*'))->where(DB::raw('DAY(created_at)'), '=', $i)->where('stats_type', "md")->count();
$stats["tru"][$i] = DB::table('users')->select(DB::raw('*'))->where(DB::raw('DAY(created_at)'), '=', $i)->count();
if ($i != 31) {
$stats["tmv"] .= ",";
$stats["tmd"] .= ",";
}
}
输出:
"tmv" => "11,4,1,13,0,5,15,2,0,24,1,7,17,18,45,14,31,61,3,1,4,1,1,27,30,47,18,60,10,0,156"
如何编辑我的查询以选择当前周的数据但仍然输出如下计数:
"11,4,1,13,0,5,15"
答案 0 :(得分:3)
您的代码会生成大量查询,这些查询非常糟糕。使用一个查询可以通过多种方式获取所需的数据。例如,使用Eloquent:
Stats::where('created_at', '>', Carbon::now()->startOfWeek())
->where('created_at', '<', Carbon::now()->endOfWeek())
->get();
如果您想要获取另一周的数据而不是当前数据,请使用另一个碳对象,例如Carbon::parse('2017-05-01')
而不是Carbon::now()