我在迁移两个具有关系的表时遇到问题。我想在product.js
迁移中添加一个外键,但它不起作用。如果我运行应用程序,await sequelize.sync();
数据库创建良好。
如何解决这个问题?我对另一个迁移user
和addresses
做了同样的事情,它和我预期的一样工作。感谢你的帮助。
== 20210124144301-创建产品:迁移=======
错误:无法创建表database_development
。products
(错误号:150“外键约束的格式不正确”)create-category.js
迁移:
"use strict";
module.exports = {
up: async (queryInterface, Sequelize) => {
await queryInterface.createTable("сategories", {
id: {
allowNull: false,
autoIncrement: true,
primaryKey: true,
type: Sequelize.INTEGER,
},
name: {
type: Sequelize.STRING,
allowNull: false,
unique: true,
},
description: Sequelize.TEXT,
createdAt: {
allowNull: false,
type: Sequelize.DATE,
},
updatedAt: {
allowNull: false,
type: Sequelize.DATE,
},
});
},
down: async (queryInterface, Sequelize) => {
await queryInterface.dropTable("сategories");
},
};
create-product.js
迁移:
"use strict";
module.exports = {
up: async (queryInterface, Sequelize) => {
await queryInterface.createTable("products", {
id: {
allowNull: false,
autoIncrement: true,
primaryKey: true,
type: Sequelize.INTEGER,
},
categoryId: {
type: Sequelize.INTEGER,
allowNull: false,
references: {
model: "categories",
key: "id",
},
},
name: {
type: Sequelize.STRING,
allowNull: false,
},
description: {
type: Sequelize.TEXT,
allowNull: false,
},
price: {
type: Sequelize.DOUBLE(11, 2).UNSIGNED,
defaultValue: 0,
},
createdAt: {
allowNull: false,
type: Sequelize.DATE,
},
updatedAt: {
allowNull: false,
type: Sequelize.DATE,
},
});
},
down: async (queryInterface, Sequelize) => {
await queryInterface.dropTable("products");
},
};
category.js
型号:
"use strict";
const { Model } = require("sequelize");
module.exports = (sequelize, DataTypes) => {
class Category extends Model {
/**
* Helper method for defining associations.
* This method is not a part of Sequelize lifecycle.
* The `models/index` file will call this method automatically.
*/
static associate(models) {
this.hasMany(models.Product, {
foreignKey: "categoryId",
});
}
}
Category.init(
{
name: {
type: DataTypes.STRING,
allowNull: false,
unique: true,
},
description: DataTypes.TEXT,
},
{
sequelize,
tableName: "categories",
modelName: "Category",
}
);
return Category;
};
product.js
型号:
"use strict";
const { Model } = require("sequelize");
module.exports = (sequelize, DataTypes) => {
class Product extends Model {
/**
* Helper method for defining associations.
* This method is not a part of Sequelize lifecycle.
* The `models/index` file will call this method automatically.
*/
static associate(models) {
this.belongsTo(models.Category, {
foreignKey: "categoryId",
});
}
}
Product.init(
{
name: {
type: DataTypes.STRING,
allowNull: false,
},
description: {
type: DataTypes.TEXT,
allowNull: false,
},
price: {
type: DataTypes.DOUBLE(11, 2).UNSIGNED,
defaultValue: 0,
},
},
{
sequelize,
tableName: "products",
modelName: "Product",
}
);
return Product;
};
2条答案
按热度按时间rvpgvaaj1#
您需要在产品和类别模型文件中添加主键(id),还需要更改模型关联。
产品.js
Category.js
ogsagwnx2#
外键必须与另一个表上的主键类型相同