I was trying to create an association without creating a foreign key constraint for a particular use case, but it doesn't look like it's possible.
I actually thought the issue was in Sequelize and reported there: https://github.com/sequelize/sequelize/issues/9303
As you can see in that issue, the reduced test case actually achieves what I want, but I don't seem able to do the exact same using sequelize-typescript. ):
My equivalent annotated model looks like this:
@Table
export class Transaction extends Model<Transaction> {
@PrimaryKey
@Column
public id: number;
@ForeignKey(() => User)
@Column(DataType.INTEGER.UNSIGNED)
public userId: number;
@BelongsTo(() => User, {
constraints: false,
})
public user: User;
}
If I remove the @ForeignKey annotation then an error is thrown:
Foreign key for "User" is missing on "Transaction".
I've tried a bunch of other combinations, but I'm out of ideas. I think it's just not possible or I'm missing something.
Hey @alfaproject , I assume you've defined the HasMany relation on User as well, right? In this case you need to set constraints: false on the has many relation too:
@Table
export class User extends Model<User> {
@HasMany(() => Transaction, {constraints: false})
transactions: Transaction[];
}
This is native sequelize behaviour. If you try it with sequelize only you can reproduce this:
const Transaction = sequelize.define('Transaction', {});
const User = sequelize.define('Transaction', {});
Transaction.belongsTo(User, {constraints: false});
User.hasMany(Transaction);
Without setting constraints: false on the hasMany relation, sequelize will set the constraints to Transaction table anyway. So set this option or if your User model don't need to know about its transactions, you can omit the hasMany relation generally.
@RobinBuschmann that seems to be the missing piece. Thank you for helping! (:
Most helpful comment
Hey @alfaproject , I assume you've defined the
HasManyrelation onUseras well, right? In this case you need to setconstraints: falseon the has many relation too:This is native sequelize behaviour. If you try it with sequelize only you can reproduce this:
Without setting
constraints: falseon the hasMany relation, sequelize will set the constraints to Transaction table anyway. So set this option or if your User model don't need to know about its transactions, you can omit the hasMany relation generally.