Skip to content

Foreign keys are different during model.create() #11574

Closed

Description

I have created a few simple models i.e. User, Role, Jurisdiction along with some associations as below:

User.belongsTo(Role, {foreignKey: { allowNull: false }, onDelete: 'CASCADE', onUpdate: 'CASCADE'});
User.belongsTo(Jurisdiction, {foreignKey: { allowNull: false }, onDelete: 'CASCADE', onUpdate: 'CASCADE'});

I have defined underscore to be true:

const sqlz = new sequelize(config.database.schema, config.database.user, config.database.password, {
    host: config.database.host,
    dialect: 'mysql',
    define:{
        underscored: true
    }
});

The User table is created as expected with the foreign keys "role_id" and "jurisdiction_id" respectively.

The issue is when I try to populate the database with some sample entries, I have to refer to the foreign keys as "RoleId" and "JurisdictionId" respectively:

Role.create({
            role: 'Developer',
            description: 'Developer'
        }).then(role => {
            Jurisdiction.create({
                jurisdiction: 'Forest'
            }).then(jurisdiction => {
                User.create({
                    username: 'test',
                    JurisdictionId: jurisdiction.id,
                    RoleId: role.id
                }).catch(err => {
                    console.error(err);
                });
            });
        });

My question is: Why are these keys not referred to by their correct underscored names?

I would expect the correct code to look like below:

Role.create({
            role: 'Developer',
            description: 'Developer'
        }).then(role => {
            Jurisdiction.create({
                jurisdiction: 'Forest'
            }).then(jurisdiction => {
                User.create({
                    username: 'test',
                    jurisdiction_id: jurisdiction.id,
                    role_id: role.id
                }).catch(err => {
                    console.error(err);
                });
            });
        });

Activity

  1. papb commented on Oct 18, 2019

    @papb
    Member

    Thanks for the report, this confusion is a known problem that I hope to solve in the near future.

    I will close this in favor of #11225 to track everything in one place.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions