Shamoon
Shamoon

Reputation: 43501

Is it possible to force a foreign key to exist using Sequelize?

My model is:

module.exports = function(sequelize, DataTypes) {
  return Person = sequelize.define('Person', {
    PersonTime: {
      type: DataTypes.INTEGER,
      allowNull: false
    },
    message: {
      type: DataTypes.STRING,
      allowNull: false
    }
  }, {
    classMethods: {
      associate: function(models) {
        return Person.hasMany(models.Thought, {
          foreignKey: 'PersonId'
        });
      }
    }
  });
};

I want to force every Person to belong to a Thought and therefore in the Thought table, I want the PersonId field to be required. How can I do this?

Upvotes: 1

Views: 4097

Answers (1)

SpaceDog
SpaceDog

Reputation: 3269

The code you want is probably:

Person.hasMany(Thought)
Thought.belongsTo(Person)

However I tried that doesn't give you a 'real' foreign key at the database level which is what you want. After some trial and error and searching I came up with this:

Thought.belongsTo(Person, { constraints: true, foreignKeyConstraint:true  } );
Person.hasMany(Thought)

When you .sync() that the SQL created is:

CREATE TABLE IF NOT EXISTS `Persons` (
    `id` INTEGER NOT NULL auto_increment , 
    `PersonTime` INTEGER NOT NULL, 
    `message` VARCHAR(255) NOT NULL,
    `createdAt` DATETIME NOT NULL, 
    `updatedAt` DATETIME NOT NULL, 
    PRIMARY KEY (`id`)
);

CREATE TABLE IF NOT EXISTS `Thoughts` (
    `id` INTEGER NOT NULL auto_increment, 
    `text` VARCHAR(255), 
    `createdAt` DATETIME NOT NULL, 
    `updatedAt` DATETIME NOT NULL, 
    `PersonId` INTEGER, 
    PRIMARY KEY (`id`), 
    FOREIGN KEY (`PersonId`) REFERENCES `Persons` (`id`)
);

More details in the documentation, although it was an answer to this question that helped me to make it work: Sequelize.js foreign key

Upvotes: 2

Related Questions