Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel Eloquent whereIn, retrieving records from database including for missing dates

I am new to Laravel.

I am building app that counts your daily steps.
And I am building API, so I need to return 0 steps when there are no results in DB for selected days in array.

But if there is data for some of the days to return actual steps and to return 0 for other days. I have tried this:

$steps = Step::whereIn('date', $dates)
             ->where('user_id', Auth::id())
             ->get();

But it returns only matches. As I wrote I want to return data for all days, not only for days in DB. Please, help :)

like image 981
J. Smith Avatar asked Mar 10 '23 09:03

J. Smith


1 Answers

This will never be possible with a simple Query as the DB can not give you anything, it does not know about. You can solve this either progrmmatically bei iterating over the result and adding all missing dates with 0-value or by adding a table to your DB which contains all dates and then left join your steps table with it in the query.

like image 177
Iarwa1n Avatar answered Apr 25 '23 05:04

Iarwa1n