Anonymous
Ошибка Sequelize Associations: «Продукт не связан с CartItem» при активной загрузке отношений
Сообщение
Anonymous » 18 янв 2025, 21:44
Я работаю над проектом Node.js с использованием Sequelize и столкнулся с ошибкой при попытке получить связанные данные с быстрой загрузкой. Вот ошибка:
Код: Выделить всё
Error fetching cart items: EagerLoadingError [SequelizeEagerLoadingError]: Product is not associated to CartItem!
Вот соответствующая часть моей настройки:
Модель CartItem
Код: Выделить всё
const { DataTypes } = require("sequelize");
const sequelize = require("../config/database");
const { CART_ITEM_STATUS } = require("../constants");
const CartItem = sequelize.define(
"CartItem",
{
productId: {
type: DataTypes.INTEGER,
references: {
model: "Products",
key: "id",
},
allowNull: false,
},
quantity: {
type: DataTypes.INTEGER,
allowNull: false,
},
purchasePrice: {
type: DataTypes.FLOAT,
defaultValue: 0,
},
status: {
type: DataTypes.ENUM(
CART_ITEM_STATUS.Not_processed,
CART_ITEM_STATUS.Processing,
CART_ITEM_STATUS.Shipped,
CART_ITEM_STATUS.Delivered,
CART_ITEM_STATUS.Cancelled
),
defaultValue: CART_ITEM_STATUS.Not_processed,
},
},
{
tableName: "cart_items",
timestamps: false,
}
);
module.exports = CartItem;
Модель продукта
Код: Выделить всё
const { DataTypes } = require("sequelize");
const sequelize = require("../config/database");
const CartItem = require("./cartitem");
const Product = sequelize.define(
"Product",
{
id: {
type: DataTypes.STRING(64),
primaryKey: true,
defaultValue: () => {
return crypto.createHash("sha256").update(uuidv4()).digest("hex");
},
},
name: {
type: DataTypes.STRING(255),
allowNull: true,
},
},
{
tableName: "products",
timestamps: false,
}
);
Product.hasMany(CartItem, {
foreignKey: "productId",
as: "items",
});
CartItem.belongsTo(Product, {
foreignKey: "productId",
as: "product",
});
module.exports = Product;
Настройка базы данных
Код: Выделить всё
CartItem.belongsTo(Product, { foreignKey: "productId", as: "product" });
Product.hasMany(CartItem, { foreignKey: "productId", as: "cartItems" });
await sequelize.sync({ alter: true });
Запрос
Код: Выделить всё
const cartItems = await CartItem.findAll({
include: [{ model: Product, as: "product" }],
});
Несмотря на правильное определение ассоциаций, ошибка сохраняется. Что может быть причиной этой проблемы и как ее устранить?
Подробнее здесь:
https://stackoverflow.com/questions/793 ... while-eage
1737225894
Anonymous
Я работаю над проектом Node.js с использованием Sequelize и столкнулся с ошибкой при попытке получить связанные данные с быстрой загрузкой. Вот ошибка: [code]Error fetching cart items: EagerLoadingError [SequelizeEagerLoadingError]: Product is not associated to CartItem! [/code] Вот соответствующая часть моей настройки: [h4]Модель CartItem[/h4] [code]const { DataTypes } = require("sequelize"); const sequelize = require("../config/database"); const { CART_ITEM_STATUS } = require("../constants"); const CartItem = sequelize.define( "CartItem", { productId: { type: DataTypes.INTEGER, references: { model: "Products", key: "id", }, allowNull: false, }, quantity: { type: DataTypes.INTEGER, allowNull: false, }, purchasePrice: { type: DataTypes.FLOAT, defaultValue: 0, }, status: { type: DataTypes.ENUM( CART_ITEM_STATUS.Not_processed, CART_ITEM_STATUS.Processing, CART_ITEM_STATUS.Shipped, CART_ITEM_STATUS.Delivered, CART_ITEM_STATUS.Cancelled ), defaultValue: CART_ITEM_STATUS.Not_processed, }, }, { tableName: "cart_items", timestamps: false, } ); module.exports = CartItem; [/code] [h4]Модель продукта[/h4] [code]const { DataTypes } = require("sequelize"); const sequelize = require("../config/database"); const CartItem = require("./cartitem"); const Product = sequelize.define( "Product", { id: { type: DataTypes.STRING(64), primaryKey: true, defaultValue: () => { return crypto.createHash("sha256").update(uuidv4()).digest("hex"); }, }, name: { type: DataTypes.STRING(255), allowNull: true, }, }, { tableName: "products", timestamps: false, } ); Product.hasMany(CartItem, { foreignKey: "productId", as: "items", }); CartItem.belongsTo(Product, { foreignKey: "productId", as: "product", }); module.exports = Product; [/code] [h4]Настройка базы данных[/h4] [code]CartItem.belongsTo(Product, { foreignKey: "productId", as: "product" }); Product.hasMany(CartItem, { foreignKey: "productId", as: "cartItems" }); await sequelize.sync({ alter: true }); [/code] [h4]Запрос[/h4] [code]const cartItems = await CartItem.findAll({ include: [{ model: Product, as: "product" }], }); [/code] Несмотря на правильное определение ассоциаций, ошибка сохраняется. Что может быть причиной этой проблемы и как ее устранить? Подробнее здесь: [url]https://stackoverflow.com/questions/79367776/sequelize-associations-error-product-is-not-associated-to-cartitem-while-eage[/url]