Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I create a required "BelongsTo" association using Sequelize?

Using Sequelize, I've created two models: User and Login.

Users can have more than one Login, but a login must have exactly one user.

How do I specify in the login model that a user must exist before a save can occur?

Current Code

var User = sequelize.define('User', {});
var Login = sequelize.define('Login', {});
Login.belongsTo(User, { foreignKey: 'userId' });

This setup would still allow a login to save before a user has been specified. For instance Login.build().save(); would execute without any validation error.

like image 914
slifty Avatar asked May 01 '15 19:05

slifty


People also ask

How do I create an association in Sequelize?

Creating associations in sequelize is done by calling one of the belongsTo / hasOne / hasMany / belongsToMany functions on a model (the source), and providing another model as the first argument to the function (the target). hasOne - adds a foreign key to the target and singular association mixins to the source.

How do you use belongsTo in Sequelize?

You can make the Task model belongs to the User model by calling the belongsTo() method from the Task model like this: Task. belongsTo(User); The belongsTo() method above will associate the Task model with the User model, adding the UserId attribute to the Task model as the foreign key constraint.

How do you create a one-to-many relationship in Sequelize?

To create a One-To-Many relationship, the hasMany and belongsTo associations are used together; To create a Many-To-Many relationship, two belongsToMany calls are used together.

What is required true in Sequelize?

This is the case because, when the where option is used inside an include , Sequelize automatically sets the required option to true . This means that, instead of an OUTER JOIN , an INNER JOIN is done, returning only the parent models with at least one matching children.


1 Answers

The answer lies in the foreignKey attribute, which actually takes in a full blown column object.

Specifically, instead if 'userId' it should be:

Login.belongsTo(User, {
  foreignKey: {
    field: 'userId',
    allowNull: false
  },
  onDelete: 'cascade'
});

Notice that onDelete has to be updated as well, because the default value for onDelete is SET NULL which may generate errors at the database level due to the rule conflict.

Thank you to the friendly folks in #sequelizejs on Freenode!

like image 63
slifty Avatar answered Oct 19 '22 04:10

slifty