Getting a default value of 0 in the DB when the column amount is null
Here's my migration file:
public function up()
{
Schema::create('income', function (Blueprint $table) {
$table->id();
$table->string('description');
$table->bigInteger('amount')->default(0);
$table->date('date');
$table->string('receipt')->nullable();
$table->foreignId('user_id')->nullable()->constrained('users')->onDelete('cascade');
$table->timestamps();
});
}
I'm looking to get an amount of 0 when no amount is entered in the date (for each day).
I tried adding ->default(0) but it doesn't seem to work.
@tykus No i didn't, do i have to make the column nullable ?
What i mean is that when i try to get the data of the amount of each day for let's say a mount, i get an array with only the non 0 numbers, while i'm looking to get an array of all the numbers whether it's 0 or a higher number.
@Mar55 that is a very different question! You want the query to return 0 for the total amount when there is no record(s) for somes dates within the period.
You can solve this in the database query (solution depends on your DBMS) or in PHP using DatePeriod
@Mar55 so... you need to generate the dates in the range; you can do this using the following SQL query:
WITH RECURSIVE dates(date) AS (
SELECT DATE(?)
UNION ALL
SELECT DATE_ADD(date,INTERVAL 1 day) FROM dates WHERE date <= ?
)
SELECT date from dates;
If you LEFT JOIN the income table; you will get your records as needed, e.g. untested but should be close
WITH RECURSIVE dates(date) AS (
SELECT DATE(?)
UNION ALL
SELECT DATE_ADD(date,INTERVAL 1 day) FROM dates WHERE date <= ?
)
SELECT date, COALESCE(SUM(income.amount, 0)) as total_amount
FROM dates
LEFT JOIN income on income.date = dates.date
GROUP BY dates.date