sequelize / sequelize

Feature-rich ORM for modern Node.js and TypeScript, it supports PostgreSQL (with JSON and JSONB support), MySQL, MariaDB, SQLite, MS SQL Server, Snowflake, Oracle DB (v6), DB2 and DB2 for IBM i.
https://sequelize.org/
MIT License
29.42k stars 4.26k forks source link

Foreign key: snake_case in DB and CamelCase in code. Does it possible? #7362

Closed maxim-danilov closed 7 years ago

maxim-danilov commented 7 years ago

Hello! I use snake_case in my MySql DB. And I use CamelCase in my JS code. So my code looks like:

sequelize.define('User', {
        'UserId': {
            field: 'user_id',
        },
        'UserName': {
            field: 'user_name',
        },

I created foreign key:

 classMethods: {
    associate: function (models) {
        User.belongsTo(models.UserRole, {
            foreignKey: {
                name: 'user_role_id',
            }
        });
    }
}

Does sequelize able to use user_role_id in DB and UserRoleId in JS code?

Thanks!

Alexsey commented 7 years ago

Yes, you need to use "field" field in model definition to set different name for model field and column name. I had use a beforeDefine Hook to set all "fields" to all models automatically in snake case based on camel case name I defined in JS. But you will also need to set createdAt, updatedAt and deletedAt explicitly for them to be also processed in hook

maxim-danilov commented 7 years ago

@Alexsey great thanks!

durango commented 7 years ago

Closing since this has been answered, thanks @Alexsey