Set defaultValue for association field that targets a unique non-primary key

19 Views Asked by At

I have two tables on Postgres:

class Account extends Model {
    static associate(models) {
      Account.belongsTo(models.Status, {
        targetKey: 'name',
        foreignKey: { name: 'status', allowNull: false, defaultValue: 'offline' },
      })
    }}

Account.init(
    {
      firstName: { type: DataTypes.STRING, allowNull: false },
      lastName: { type: DataTypes.STRING, allowNull: false },
      email: { type: DataTypes.STRING, allowNull: false, unique: true },
      password: { type: DataTypes.STRING, allowNull: false },
      image: DataTypes.STRING,
      telephone: DataTypes.STRING,
    },
    {
      sequelize,
      tableName: 'accounts',
    },
)
  class Status extends Model {}
  Status.init(
    {
      name: { type: DataTypes.STRING, allowNull: false, unique: true },
    },
    {
      sequelize,
      tableName: 'statuses',
    },
  )

I want to set the default association Status for Account to be the record with the name "offline". And in top of that I want to reference not the primary key, but the unique value on the name column.

The generated query is: ALTER TABLE "accounts" ALTER COLUMN "status" SET NOT NULL;ALTER TABLE "accounts" ALTER COLUMN "status" SET DEFAULT 'offline' REFERENCES "statuses" ("name") ON DELETE NO ACTION ON UPDATE CASCADE;ALTER TABLE "accounts" ALTER COLUMN "status" TYPE VARCHAR(255);

But it throws the following error when doing Sequelize.sync() : syntax error at or near «REFERENCES»

0

There are 0 best solutions below