Reputation: 462
I am trying to get this current week's data from my table
I have the following code which gives me 31 days of data (A month but it's separated which is what I need)
$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"] .= ",";
}
}
Output:
"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"
How do I edit my query to select this current week's data but still output the count like:
"11,4,1,13,0,5,15"
Upvotes: 5
Views: 6288
Reputation: 163758
Your code generates a lot of queries which is really bad. There are many ways to get data you want with one query. For example, using Eloquent:
Stats::where('created_at', '>', Carbon::now()->startOfWeek())
->where('created_at', '<', Carbon::now()->endOfWeek())
->get();
If you want to get data for another week and not the current one, use another Carbon object like Carbon::parse('2017-05-01')
instead of Carbon::now()
Upvotes: 12