일대다 관계

다대다 관계

**//**Plant **테이블 정의하기**
"use strict";

const { Model } = require("sequelize");
module.exports = (sequelize, DataTypes) => {
  class Plant 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) {
      // define association here
      this.hasMany(models.Plant_category);
      **this.belongsToMany(models.User, { through: "Interiors" });**
    }
  }
  Plant.init(
    {
      name: DataTypes.STRING(50),
      image: DataTypes.STRING(2083),
      description: DataTypes.STRING(500),
    },
    {
      sequelize,
      modelName: "Plant",
    }
  );
  return Plant;
};

**//User 테이블 정의하기**
"use strict";
const { Model } = require("sequelize");
module.exports = (sequelize, DataTypes) => {
  class User 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) {
      // define association here
      this.belongsToMany(models.Plant, { through: "Interiors" });
    }**
  }
  User.init(
    {
      email: DataTypes.STRING(50),
      password: DataTypes.STRING(70),
      nickname: DataTypes.STRING(10),
    },
    {
      sequelize,
      modelName: "User",
    }
  );
  return User;
};
"use strict";

module.exports = {
  async up(queryInterface, Sequelize) {
    await queryInterface.createTable("Interiors", {
      id: {
        allowNull: false,
        autoIncrement: true,
        primaryKey: true,
        type: Sequelize.INTEGER,
      },
      **userId: {
        type: Sequelize.INTEGER,
        allowNull: false,
        references: {
          model: "Users",
          key: "id",
        },
        onUpdate: "CASCADE",
        onDelete: "CASCADE",
      },
      plantId: {
        type: Sequelize.INTEGER,
        allowNull: false,
        references: {
          model: "Plants",
          key: "id",
        },
        onUpdate: "CASCADE",
        onDelete: "CASCADE",
      },**
      image: {
        allowNull: false,
        type: Sequelize.STRING(2083),
      },
      content: {
        allowNull: false,
        type: Sequelize.STRING(1000),
      },
      createdAt: {
        allowNull: false,
        type: Sequelize.DATE,
      },
      updatedAt: {
        allowNull: false,
        type: Sequelize.DATE,
      },
    });
  },

  async down(queryInterface, Sequelize) {
    await queryInterface.dropTable("Interiors");
  },
};

ref

https://medium.com/@andrewoons/how-to-define-sequelize-associations-using-migrations-de4333bf75a7