首页 > 解决方案 > 续集 addConstraint 语法

问题描述

我试图添加两个表,播放列表和标签。标签可选地有一个播放列表,许多播放列表可以与同一个标签相关。

为了将外键约束添加到播放列表,我尝试使用 addConstraint 添加它。文档对此很糟糕。

这就是我所拥有的:

"use strict";

module.exports = {
  up: async (queryInterface, Sequelize) => {
    await queryInterface.createTable("Playlist", {
      id: { type: Sequelize.STRING, primaryKey: true, allowNull: false },
      track_uri: Sequelize.STRING,
      track: Sequelize.STRING(150),
      artist: Sequelize.STRING(150),
      added_at: {
        type: Sequelize.DATE,
        defaultValue: new Date(),
        allowNull: false,
      },
      created_at: {
        type: Sequelize.DATE,
        defaultValue: new Date(),
        allowNull: false,
      },
      is_album_track: Sequelize.BOOLEAN,
      label: { type: Sequelize.STRING, unique: true },
    });

    await queryInterface.createTable("Label", {
      id: { type: Sequelize.STRING, primaryKey: true },
      playlist_link: {
        type: Sequelize.STRING(150),
        unique: true,
        allowNull: false,
      },
      password: { type: Sequelize.STRING, allowNull: false },
      email: { type: Sequelize.STRING, allowNull: false },
      playlist: {
        type: Sequelize.STRING,
        foreignKey: true,
        references: {
          model: "Playlist",
          label: "id",
        },
      },
    });

    await queryInterface.addConstraint("Playlist", {
      type: "foreign key",
      fields: ["label"],
      name: "label_fkey",
      references: {
        table: "Label",
        field: "id",
      },
      onDelete: "cascade",
      onUpdate: "cascade",
    });
  },

  down: async (queryInterface, Sequelize) => {
    await queryInterface.dropTable("Label");
    await queryInterface.dropTable("Playlist");
  },
};

我收到此错误:

ERROR: column "label" referenced in foreign key constraint does not exist

标签: node.jssequelize.js

解决方案


推荐阅读