Sequelize addConstraint syntax

Viewed 713

Im trying to add two tables, Playlist and Label. Label optionally has a playlist, many playlists can relate to the same label.

In order to add the foreign key constraint to playlist im trying to add it using addConstraint. The docs are terrible on this .

This is what i have:

"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");
  },
};

Im getting this error:

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

0 Answers
Related