提前致谢。抱歉,如果这是一个愚蠢的错误,而且我是序列化新手,但我在两个不同的文件中有 2 个模型
第一个用户
module.exports=(sequelize,DataTypes)=>{
const User=sequelize.define("User",{
email:{
type:DataTypes.STRING,
primaryKey:true,
allowNull:false,
validate:{
notEmpty:true
},
},
password:{
type:DataTypes.STRING,
allowNull:false,
validate:{
notEmpty:true
},
}
},
{
freezeTableName: true
}
)
return User;
};
第二节
module.exports=(sequelize,DataTypes)=>{
const Section=sequelize.define("Section",{
HeroSec:{
type:DataTypes.BOOLEAN,
defaultValue: true,
allowNull:false,
validate:{
notEmpty:true
},
}
},
{
freezeTableName: true
});
return Section;
}
我正在尝试在两个表用户和部分之间创建关系,以电子邮件为主键以及另一个表的外键,这在错误后给我带来错误
关系代码:
const Section = require("./Section");
const User = require("./User");
module.exports=(sequelize)=>{
const user=User(sequelize)
const section=Section(sequelize)
user.hasOne(section);
sequelize.sync({alter:true}).then(()=>{
//
}).catch((err)=>{
console.log(err)
})
};
请帮助我使用电子邮件作为密钥连接这两个,抱歉,如果这是一个幼稚的错误,谢谢:)
User
要使用 Sequelize 在您的模型之间建立一对一的关系Section
,您需要在Section
模型中显式定义外键以引用模型email
的字段User
。您当前的代码没有正确处理这种关系,并且没有定义外键。用户模型(User.js)
截面模型 (Section.js)
关系定义(index.js 或定义关系的任何主文件)
User
模型email
作为主键。Section
键定义模型。email
email
User
User.hasOne(Section, { foreignKey: 'email' })
:这建立了一种一对一的关系,其中 aUser
可以有一个Section
。Section.belongsTo(User, { foreignKey: 'email' })
:这告诉 Sequelize与使用该字段Section
相关联。User
email
通过确保正确定义外键并正确设置关系,您应该能够使用 作为
email
键连接这两个模型,而不会出现错误。