sequelize-typescript
sequelize-typescript copied to clipboard
foreign key cannot be non-nullable
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
I think you can use the AllowNull decorator
Just import it and use it like:
@ForeignKey(...)
@AllowNull(false)
@Column