Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to set a default date using knex? #3821

Open
expelliamus opened this issue Apr 22, 2020 · 3 comments
Open

How to set a default date using knex? #3821

expelliamus opened this issue Apr 22, 2020 · 3 comments

Comments

@expelliamus
Copy link

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'

@oleh-melnychuk
Copy link

oleh-melnychuk commented Feb 10, 2022

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

@vitaliimelnychuk
Copy link

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.

@wamiikechukwu
Copy link

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]));

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants