Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to choose name of Foreign Key column using Sequelize and mySql?

I am using sequelize to model a mySql-database schema in my node-application. An extract of my model looks like this: I have a company-table and a department-table. A company can have multiple departments and a department belongs to only one company. I modeled this as follows:

The company-table:

module.exports = function(sequelize, DataTypes){
return Company = sequelize.define('Company', {
    companyId: {
        type: DataTypes.INTEGER,
        primaryKey: true,
        allowNull: false,
        autoIncrement: true,
        unique: true            
    },
    name: {
        type: DataTypes.STRING,
        allowNull: false
    }
})}

The department-table:

var Company = require('./company');

module.exports = function(sequelize,DataTypes) {
return Department = sequelize.define('Department', {
    departmentId: {
        type: DataTypes.INTEGER,
        primaryKey: true,
        allowNull: false,
        autoIncrement: true,
        unique: true
    },
    name: {
        type: DataTypes.STRING,
        allowNull: false            
    },
    companyId: {
        type:           DataTypes.INTEGER,
        references:     'Companies',
        referencesKey:  'companyId',
        onDelete:       'cascade'
    }
});}

To actually store this schema in the database I use the following code:

var db = require('../models/index');
db["Company"].hasMany(db["Department"], {as: 'departments'});
db["Department"].belongsTo(db["Company"], {foreignKey: 'companyId', foreignKeyConstraint: true});

models.sequelize.sync().complete(function(err){
    //irrelevant for the problem
});

The problem is that this code creates 2 foreign keys in the department table. One on the field "companyId" (as expected) but also one on the field "CompanyCompanyId", a field that is automatically generated.

How can I make sure that only the foreign key I defined ('companyId') is used and created?

like image 451
Simon Avatar asked Jan 20 '15 22:01

Simon


People also ask

How do I specify a foreign key in Sequelize?

Sequelize association methods also accept an options object that you can use to configure the details of the association. For example, you can change the foreign key name on the table by adding the foreignKey property: User. hasOne(Invoice, { foreignKey: "invoice_creator", // UserId -> invoice_creator });

How do you find the table name in Sequelize model?

Detail about Using model Class getTableName()Have schema => return { tableName, schema, delimter } object. Depending on that we can access in one of the way: // model has no schema const tableName = Course. getTableName(); // or // model has schema const tableName = Course.

Does Sequelize work with MySQL?

Sequelize is a Node. js-based Object Relational Mapper that makes it easy to work with MySQL, MariaDB, SQLite, PostgreSQL databases, and more. An Object Relational Mapper performs functions like handling database records by representing the data as objects.


1 Answers

I managed to fix the problem:

Instead of only using the "foreignKey"-option in the belongsTo-statement, it should also be used in the "hasMany"-statement.

The two models that were posted in the original question remained the same. The only thing I had to change was the location of the foreignKey option:

var db = require('../models/index');
db["Company"].hasMany(db["Department"], {as: 'departments'});
db["Department"].belongsTo(db["Company"], {foreignKey: 'companyId', foreignKeyConstraint: true});

changed to:

var db = require('../models/index');
db["Company"].hasMany(db["Department"], { foreignKey: 'companyId'});
db["Department"].belongsTo(db["Company"], {foreignKey: 'companyId'});
like image 137
Simon Avatar answered Oct 13 '22 21:10

Simon