最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Sequelize Associations Error: "Product is not associated to CartItem" while eager loading relatio

programmeradmin1浏览0评论

I'm working on a Node.js project using Sequelize, and I'm encountering an error when trying to fetch associated data with eager loading. Here's the error:

Error fetching cart items: EagerLoadingError [SequelizeEagerLoadingError]: Product is not associated to CartItem!

Here’s the relevant part of my setup:

CartItem Model

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;

Product Model

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;

Setup DB

CartItem.belongsTo(Product, { foreignKey: "productId", as: "product" });
Product.hasMany(CartItem, { foreignKey: "productId", as: "cartItems" });

await sequelize.sync({ alter: true });

Query

const cartItems = await CartItem.findAll({
  include: [{ model: Product, as: "product" }],
});

Despite defining associations properly, the error persists. What might be causing this issue, and how can I fix it?


与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论