Rediska's avatar

How to group the last added records by days, taking into account the days without records?

To get the records for the last week I use this code:

use Carbon\Carbon;
use Illuminate\Support\Facades\DB;
public function getProductsWeek()
    {
        $dates = collect();
        $startDate = Carbon::now()->subDays(7)->startOfDay();
        $endDate = Carbon::now()->endOfDay();

        while ($startDate <= $endDate) {
            $dates->push($startDate->format('Y-m-d'));
            $startDate->addDay();
        }

        return DB ::table('dates')
            ->leftJoinSub(
                Product::selectRaw('DATE(created_at) as date, COUNT(*) as products')
                    ->where('created_at', '>=', Carbon::now()->subDays(7))
                    ->groupBy('date'),
                'products',
                'dates.date',
                '=',
                'products.date'
            )
            ->orderBy('dates.date', 'ASC')
            ->get(['dates.date', DB::raw('COALESCE(products.products, 0) as products')])
            ->toArray();
    }

He should check the latest entries by day. And if there was no record on that day, return 0. But in the end I get this error: Base table or view not found: 1146 Table 'marketplace.dates' doesn't exist (SQL: select dates.date, COALESCE(products.products, 0) as products from dates left join (select DATE(created_at) as date, COUNT(*) as products from products where created_at >= 2023-05-25 08:30:54 and products.deleted_at is null group by date) as products on dates.date = products.date order by dates.date asc)

What am I doing wrong?

0 likes
0 replies

Please or to participate in this conversation.