sequelize-typescript
sequelize-typescript copied to clipboard
How to use @hasOne?
Issue
Versions
- sequelize: ^6.16.1
- sequelize-typescript: ^2.1.2
- typescript: ^4.5.5
Issue type
- [x] question
- [ ] feature request
- [ ] bug report
How to use @hasOne?
There are examples for @hasMany @belongsTo, but how to use @hasOne is unclear?
@zdev-online
From the official doc for sequelize:
The A.hasOne(B) association means that a One-To-One relationship exists between A and B, with the foreign key being defined in the target model (B).
The A.belongsTo(B) association means that a One-To-One relationship exists between A and B, with the foreign key being defined in the source model (A).
@zdev-онлайн
Из официального документа для продолжения:
Ассоциация A.hasOne(B) означает, что между A и B существует отношение «один к одному», при этом внешний ключ определяется в целевой модели (B).
Ассоциация A.belongsTo(B) означает, что между A и B существует отношение «один к одному», при этом внешний ключ определяется в исходной модели (A).
Can I have a sample code?
@zdev-online
There are many examples in the repository test/specs/association.spec.ts
file
one of the examples:
@Table
class User extends Model {
@Column
name: string;
@HasOne(() => Address, { foreignKey: 'userId' })
address: any; // "any" because of order of execution (in separate classes this will work, I promise)
}
@Table
class Address extends Model {
@Column
street: string;
@Column
zipCode: string;
@Column
city: string;
@Column
country: string;
@ForeignKey(() => User)
@Column
userId: number;
@BelongsTo(() => User)
user: User;
}