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.
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.
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.
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.
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.
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With