javascript - How to establish relationships using Sequelize -
i hoping me correctly setup relationships in sequelize. believe have models correctly setup, not sure have never used api before, , documentation confusing. have attached picture of think tables should like, , below code snippets of think should happen can't tell.
any pointers on if db design accurate or not, , whether or not sequelize associations (hasmany, belongsto, etc) correct super helpful!
users model
'use strict'; module.exports = function(sequelize, datatypes) { //define user table, , columns, data types, attributes var user = sequelize.define('user', { user_id: {...}, user_name: {...} }, { //define constraints, such foreign key classmethods:{ associate: function(models) { user.belongstomany(models.group); user.hasmany(models.old_password); } } }); return user; };
roles model
'use strict'; module.exports = function(sequelize, datatypes){ var role = sequelize.define('role',{ role_id: {...}, role_name:{...} }, { //define constraints, such foreign key classmethods:{ associate: function(models){ role.belongsto(models.user); } } }); return role; };
groups model
'use strict'; module.exports = function(sequelize, datatypes){ var group = sequelize.define('group', { group_id: {...}, group_name: {...}, }); return group; };
password model
'use strict'; module.exports = function(sequelize, datatypes){ //define table, , columns, data types, attributes var old_password = sequelize.define('old_password', { old_password_id: {...}, old_password_value: {...} }, { //define constraints, such foreign key classmethods:{ associate: function(models){ old_password.hasone(models.user); } } }); return old_password; };
the database design accurate. however, need define relationship between user
, group
. it's many-to-many relationship you'll need add constraint user
model:
classmethods:{ associate: function(models){ user.belongstomany(models.group, { // define join table through: 'user_group', // define foreign key foreignkey: 'group_id' }); models.group.belongstomany(user, { through: 'user_group', foreignkey: 'user_id' }); user.hasmany(models.old_password); } }
Comments
Post a Comment