[TIL] 시퀄라이즈 외래키

김민재·2023년 11월 12일
0

TIL

목록 보기
48/172

출처 https://loy124.tistory.com/374
외래키를 설정하는 법을 찾아보겠습니다람쥐
1.

npx sequelize migration:generate --name fk-comment

외래키를 위해 파일 생성

  1. 파일에 들어가서
"use strict";

/** @type {import('sequelize-cli').Migration} */
module.exports = {
  async up(queryInterface, Sequelize) {
    await queryInterface.addColumn("Products", "userId", {
      type: Sequelize.INTEGER,
    });
    // Products 테이블에 userId라는 컬럼을 추가해준다
    await queryInterface.addConstraint("Products", {
      fields: ["userId"], // userId에 설정
      type: "foreign key", // 외래키를 설정
      name: "user_product_id_fk", // 파일 네임
      references: {
        table: "Signs", //어디를 참조할지
        field: "id",
      },
      onDelete: "cascade",
      onUpdate: "cascade",
    });
  },

  async down(queryInterface, Sequelize) {
    await queryInterface.removeColumn("Products", "userId");
  },
};
  1. models 파일들도 바꿔줘야한다.
    static associate(models) {
      models.Products.belongsTo(models.Signs, { foreignKey: "userId" });
    }

// 1:1 관계 (상품은 회원을 하나만 가져올 수 있다.)

   static associate(models) {
      models.Signs.hasMany(models.Products, { foreignKey: "userId" });
    }

// 회원은 여러개의 상품을 받을 수 있다. 1:n(m)관계

 npx sequelize seed:generate --name post
 npx sequelize seed:generate --name comment

seeders에 파일 생성

"use strict";

module.exports = {
  up: async (queryInterface, Sequelize) => {
    const userId = await queryInterface.bulkInsert(
      "Sings",
      [
        {
          title: "test1",
          content: "test1",
          createdAt: new Date(),
          updatedAt: new Date(),
        },
        {
          title: "test2",
          content: "test2",
          createdAt: new Date(),
          updatedAt: new Date(),
        },
        {
          title: "test3",
          content: "test3",
          createdAt: new Date(),
          updatedAt: new Date(),
        },
      ],
      { returning: ["id"] }
    );
    await queryInterface.bulkInsert("Products", [
      {
        comment: "test1",
        createdAt: new Date(),
        updatedAt: new Date(),
        userId: userId,
      },
      {
        comment: "test2",
        createdAt: new Date(),
        updatedAt: new Date(),
        userId: userId,
      },
      {
        comment: "test3",
        createdAt: new Date(),
        updatedAt: new Date(),
        userId: userId,
      },
    ]);
  },
// Signs와 Products에 userId를 넣어준다
  down: async (queryInterface, Sequelize) => {
    await queryInterface.bulkDelete("Sings", null, {});
    await queryInterface.bulkDelete("Products", null, {});
    /**
     * Add commands to revert seed here.
     *
     * Example:
     * await queryInterface.bulkDelete('People', null, {});
     */
  },
};

그리고 자동외래키설정 수동이 있는데,
나는 수동을 했다.

    const userId = res.locals.user.id;
    // token 설정한 것 res.locals.user
        await Products.create({
      // 외래키에 userId를 넣어준다.
      userId,
      title,
      content,
      status,
    });
profile
개발 경험치 쌓는 곳

0개의 댓글

관련 채용 정보