Sequelize Model Relationship

Multi tool use
Multi tool use


Sequelize Model Relationship



I have 2 models here -



user.js


module.exports = (sequelize, DataType) => {

const User = sequelize.define('user', {
id: {
autoIncrement: true,
primaryKey: true,
type: DataType.INTEGER
},
username: {
type: DataType.STRING,
unique: true,
validate: {
len:
{ args: [4, 20], msg: "Username should be contain 4-20 characters." },
isAlphanumeric:
{ msg: "Only letters and numbers are allowed" }
}
},
email: {
type: DataType.STRING,
unique: true,
validate: {
isEmail:
{ msg: "Provide proper email" }
}
},
password: DataType.STRING,
emailverified: DataType.BOOLEAN
});

User.associate = function (models) {
// associations can be defined here
};



userprofile.js


module.exports = (sequelize, DataTypes) => {
var userprofile = sequelize.define('userprofile', {
nickName: DataTypes.STRING,
firstName: DataTypes.STRING,
middleName: DataTypes.STRING,
lastName: DataTypes.STRING,
gender: DataTypes.INTEGER,
age: DataTypes.INTEGER,
country: DataTypes.INTEGER,
steamUrl: DataTypes.STRING,
city: DataTypes.INTEGER,
status: DataTypes.STRING
}, {});
userprofile.associate = function (models) {
// associations can be defined here
};
return userprofile;
};



Can someone give an example on how to set 1: N relationship from user to userprofile i.e, 1 user can have N number of userprofiles and also by creating this relationship will a record be auto-generated under userprofiles table whenever a user is created?



Thank you




1 Answer
1



Did some research -
ref: https://github.com/sequelize/express-example/blob/master/models/user.js


module.exports = (sequelize, DataType) => {

const User = sequelize.define('user', {
id: {
autoIncrement: true,
primaryKey: true,
type: DataType.INTEGER
},
username: {
type: DataType.STRING,
unique: true,
validate: {
len:
{ args: [4, 20], msg: "Username should be contain 4-20 characters." },
isAlphanumeric:
{ msg: "Only letters and numbers are allowed" }
}
},
email: {
type: DataType.STRING,
unique: true,
validate: {
isEmail:
{ msg: "Provide proper email" }
}
},
password: DataType.STRING,
emailverified: DataType.BOOLEAN
});

User.associate = (models) => {
User.hasMany(models.userprofile, {
foreignKey: 'userid',
});
};



The above code creates a foreign key in userprofile table and auto-generation is not done.






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

ZCvG50cQQkv9ZT zsJsF,RPrWcBJdUJe2B4jgnNsde6jRooqx,UZPk,v6XUdZd0I vwiXjAyoi7DxvSEtCnOPON9tC
eddMAifA9IGzSvKQL 5Ff,t2i9gZCiMaJ 8f3RUHzDCRzlSRpH,OXNj,34rFmPOtYWCVPp JmC0utC,nbsyoFp veIzs

Popular posts from this blog

Rothschild family

Boo (programming language)