'Creating with Associations Sequelize

I have 2 models : cart and cartdetail . I want to create data in model cart and model cartdetail also auto create .

However, it's only create in table carts, table cartdetails not create. how can I create it with association to cartdetaile. Please help me. Thank you very much.

cart.js

  "use strict";
const { Model } = require("sequelize");
module.exports = (sequelize, DataTypes) => {
  class cart 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) {
      cart.hasMany(models.cartdetail, {
        foreignKey: "cartID",
      });
    }
  }
  cart.init(
    {
      userId: DataTypes.INTEGER,
      payment_method: DataTypes.STRING,
      price: DataTypes.INTEGER,
      status: DataTypes.INTEGER,
      address_id: DataTypes.INTEGER,
    },
    {
      sequelize,
      modelName: "cart",
    }
  );
  return cart;
};

cartdetail.js

"use strict";
const { Model } = require("sequelize");
module.exports = (sequelize, DataTypes) => {
  class cartdetail 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) {
      cartdetail.belongsTo(models.cart);
    }
  }
  cartdetail.init(
    {
      cartID: DataTypes.INTEGER,
      producID: DataTypes.INTEGER,
      quality: DataTypes.INTEGER,
      price: DataTypes.INTEGER,
    },
    {
      sequelize,
      modelName: "cartdetail",
    }
  );
  return cartdetail;
};

Example:

await db.cart.create(
          {
            userId: data.jwtDecoded,
            payment_method: data.body.payment_method,
            price: data.body.total,
            status: data.body.status,
            address_id: data.body.address_id,
            cartdetail: [{ quality: "123" }],
          },
          {
            include: [db.cartdetail],
          }
        );


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source