我这里有 2 个模型 -
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;
};
有人可以举例说明如何设置从用户到用户个人资料的1:N关系,即1个用户可以拥有N个用户配置文件,并且通过创建此关系,每当创建用户时,是否会在用户配置文件表下自动生成一条记录?
谢谢
最佳答案
做了一些研究 - 引用: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',
});
};
上面的代码在用户配置文件表中创建了一个外键,并且没有完成自动生成。
关于mysql - 序列化模型关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51117509/