orm - How to implement one-to-many relationship with join table using sequelize-npm in node.js -
i writing rest apis in node.js sequelize mysql orm. know, how achieve n:m relationship between 2 tables using sequelize association. defined here in official documentation of sequelize.
i want achieve one-to-many relationship using join table.
my approach achieve :
parent.model.js
module.exports = function(sequelize, datatypes){ var parent = sequelize.define('parent', { parent_id:{ type:datatypes.integer, field:'parent_id', primarykey: true, autoincrement: true, unique:true }, parent_name:{ type: datatypes.string, field: 'parent_name' }, }, { classmethods:{ associate:function(models){ parent.belongstomany(models.child, { through:'parent_child_mapping', foreignkey:'parent_id' }); } } } ); return parent; }
child.model.js
module.exports = function(sequelize, datatypes){ var child = sequelize.define('child', { child_id:{ type:datatypes.integer, field:'child_id', primarykey: true, autoincrement: true, unique:true }, child_name:{ type: datatypes.string, field: 'child_name' }, }, { classmethods:{ associate:function(models){ child.belongsto(models.parent, { through:'parent_child_mapping', foreignkey:'child_id' }) } } } ); return child; }
after syncing new table structure follows :
my problem:
- why sequelize creating foreign key childchildid ?
- will work ?
in parent.model.js should write
parent.hasmany
instead of
parent.belongstomany
if write "belongstomany" creates n:m relation described in here http://docs.sequelizejs.com/en/latest/api/associations/belongs-to-many/
edit: here doc "hasmany" : http://docs.sequelizejs.com/en/latest/api/associations/has-many/
Comments
Post a Comment