sequelize-typescript icon indicating copy to clipboard operation
sequelize-typescript copied to clipboard

foreign key cannot be non-nullable

Open chan9948 opened this issue 2 years ago • 1 comments

Issue

foreignKey cannot be set with allowNull:false

//BaseModel.ts
@Table({ version: true })
export abstract class BaseModel<
  TModelAttributes,
  TCreationAttributes,
> extends Model<TModelAttributes, TCreationAttributes> {
  @PrimaryKey
  @Default(DataType.UUIDV4)
  @Column(DataType.UUID)
  id: CreationOptional<string>;
}


//UserModel.ts
@Table({ tableName: 'User' })
export class UserModel extends BaseModel<
  InferAttributes<UserModel>,
  InferCreationAttributes<UserModel>
> {
  @Column
  name: string;
}


//PostModel.ts
@Table({ tableName: 'Post' })
export class PostModel extends BaseModel<
  InferAttributes<PostModel>,
  InferCreationAttributes<PostModel>
> {
  @Column
  content: string;

  @ForeignKey(() => UserModel)
  @Column({ allowNull: false }) //this line causes the problem
  userId: string;
  @BelongsTo(() => UserModel)
  user: NonAttribute<UserModel>;
}

if I set @Column({ allowNull: false }) in the PostModel, this error comes up: ERROR [SequelizeModule] Unable to connect to the database. Retrying (1)...

Versions

  • sequelize: 6.21.6
  • sequelize-typescript: 2.1.3
  • typescript: 4.3.5

chan9948 avatar Jan 31 '23 08:01 chan9948

I think you can use the AllowNull decorator Just import it and use it like:

@ForeignKey(...)
@AllowNull(false)
@Column

lik3as avatar Oct 27 '23 19:10 lik3as