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

How to use @hasOne?

Open zdev-online opened this issue 3 years ago • 3 comments

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 avatar Feb 17 '22 13:02 zdev-online

@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).

sluchznak avatar Feb 17 '22 15:02 sluchznak

@zdev-онлайн

Из официального документа для продолжения:

Ассоциация A.hasOne(B) означает, что между A и B существует отношение «один к одному», при этом внешний ключ определяется в целевой модели (B).

Ассоциация A.belongsTo(B) означает, что между A и B существует отношение «один к одному», при этом внешний ключ определяется в исходной модели (A).

Can I have a sample code?

zdev-online avatar Feb 17 '22 18:02 zdev-online

@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;
}

stringang avatar Nov 05 '22 15:11 stringang