刚开始使用sequelize,我试图使用关联函数设置一个外键。我有两个模特:
用户:
const User = sequelize.define("User", {
userId: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
allowNull: false,
unique: true,
primaryKey: true
},
email: {
type: DataTypes.STRING,
allowNull: false,
unique: true,
validate: {
isEmail: true,
notNull: true,
notEmpty: true
}
},
userName: {
type: DataTypes.STRING,
allowNull: false,
validate: {
notNull: true,
notEmpty: true
}
},
password: {
type: DataTypes.STRING,
allowNull: false,
validate: {
notNull: true,
notEmpty: true
}
},
profileImage: {
type: DataTypes.STRING(300),
validate: {
isUrl: true
}
},
rating: {
type: DataTypes.DECIMAL(10, 2),
validate: {
isDecimal:true
}
}
},{
tableName:"user"
}
);员额:
const Post = sequelize.define("Post", {
postId: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
allowNull: false,
unique: true,
primaryKey: true
},
title: {
type: DataTypes.STRING,
allowNull: false,
validate: {
notEmpty: true
}
},
content: {
type: DataTypes.TEXT,
allowNull: false,
validate: {
notEmpty: true
}
},
status: {
type: DataTypes.STRING,
defaultValue: "OPEN",
allowNull: false,
validate: {
notEmpty: true
}
}
}, {
tableName: "post"
}
);我目前正在我的resetTables.js中设置如下外键:
User.hasMany(Post);
Post.belongsTo(User, {
foreignKey: {
name: "userId",
type: DataTypes.UUID,
allowNull: false,
validate: {
notNull: true
}
},
onDelete: "CASCADE"
});但出于某种原因,我不断得到一个额外的列为外键:
Executing (default): CREATE TABLE IF NOT EXISTS "post" ("postId" UUID NOT NULL UNIQUE , "title" VARCHAR(255) NOT NULL, "content" TEXT NOT NULL, "status" VARCHAR(255) NOT NULL DEFAULT 'OPEN', "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL, "updatedAt" TIMESTAMP WITH TIME ZONE NOT NULL, "userId" UUID NOT NULL REFERENCES "user" ("userId") ON DELETE CASCADE ON UPDATE CASCADE, "UserUserId" UUID REFERENCES "user" ("userId") ON DELETE SET NULL ON UPDATE CASCADE, PRIMARY KEY ("postId"));如您所见,我正在正确创建"userId“列,但出于某种原因,另一个名为"UserUserId”的列也正在创建?我还有其他类似定义的关联,只有这个表有这个问题。任何帮助都将不胜感激。
我使用的是续写V6和NodeJS以及ElephantSQL上的PostgreSQL。
发布于 2022-08-01 18:05:42
我知道我迟到了,但我也遇到了同样的问题,我发现这是因为belongTo,您只需要在声明1:N关联时使用hasMany。
https://stackoverflow.com/questions/69826653
复制相似问题