knex icon indicating copy to clipboard operation
knex copied to clipboard

How to set a default date using knex?

Open expelliamus opened this issue 5 years ago • 3 comments

I'm using knex and I'm trying to set a defaut date that takes in consideration the current date and sum it of one day, so for example the default date for today should be:

23/04/2020

In my migration file I've added this:

exports.up = async (knex, Promise) => (await knex.schema.hasTable('access-code'))
    ? null
    : knex.schema.createTable('access-code', function (table) {
        table.increments('id')
        table.date('expire_at').defaultTo([knex.fn.now(), 1])
    });

but this return:

default character set utf8mb4 - ER_INVALID_DEFAULT: Invalid default value for 'expire_at'

expelliamus avatar Apr 22 '20 17:04 expelliamus

Hi, everyone. Have the same issue, maybe someone has the solution?

oleh-melnychuk avatar Feb 10 '22 21:02 oleh-melnychuk

Based on the documentation from Mysql https://dev.mysql.com/doc/refman/8.0/en/data-type-defaults.html you probably need to set the Date string instead of timestamp.

I can't find anything in Knex documentation that could help here so I used the syntax below by using knex.raw.

 table.date('expire_at').defaultTo(knex.raw('(CURRENT_DATE())'))

If you are using different adapter you might check if your database supports that function or has different one.

vitaliimelnychuk avatar Aug 11 '22 10:08 vitaliimelnychuk

I am facing this same issue, i want to set an expire_at column, that sets a future date: This is the knex code: table.timestamp('expires_at').notNullable().defaultTo(knex.raw('DATE_ADD(?, INTERVAL ? DAY)', [knex.fn.now(), 1]));

wamiikechukwu avatar May 01 '24 08:05 wamiikechukwu