how to create association instance from source instance with sequelize-typescript
Asked Answered
L

2

7

I have 1:n association Company -> CompanySettings, what I want is, I find Company by Id then create companySettings by that instance and automatically fill the foreign key attribute

using sequelize-typescript

I have tried $get, $add, $count from association function and its works

but when I try $create function it gives me the errors

Company Class

@Table({
  tableName: 'company',
})
export class Company extends Model<Company> {

  @Column({ allowNull: false, type: DataType.STRING(50) })
  name: string

  @CreatedAt
  @Column({ field: 'created_at' })
  createdAt: Date

  @UpdatedAt
  @Column({ field: 'updated_at' })
  updatedAt: Date

  @Column({ field: 'is_deleted', defaultValue: 'f', type: DataType.BOOLEAN })
  isDeleted: boolean

  @HasMany(() => CompanySettings)
  settings: CompanySettings[]

CompanySettings class

@Table({
  tableName: 'company_settings',
})
export class CompanySettings extends Model<CompanySettings> {

  @ForeignKey(() => Company)
  @Column
  idCompany: number

  @BelongsTo(() => Company)
  company: Company

  @Column({ type: DataType.ENUM('default', 'alwaysApprove', 'alwaysAsking') })
  defaultBookingApproval: defaultBookingOptions

  @Column({ type: DataType.SMALLINT })
  budgetPeriod: number

  @Column({ type: DataType.CHAR(2) })
  startDate: string

  @CreatedAt
  @Column
  createdAt: Date

  @UpdatedAt
  @Column
  updatedAt: Date

  @Column({ defaultValue: 'f', type: DataType.BOOLEAN })
  isDeleted: boolean

controller

const companies = await Company.findOne()

    return await companies.$create('settings', { startDate: '22' })

After finding the source instance, I want to create new instance related to the source instance

But the errors I got is shown below

TypeError: this[("create" + string_1.capitalize(...))] is not a function

tell me where am i wrong ?

Laity answered 26/10, 2019 at 16:20 Comment(0)
E
0

if you want create one setting, you should write code like below

companies.$create('setting', { startDate: '22 })

instead of companies.$create('settings', { startDate: '22' })

if you want create bulk, you should like below

companies.$create('settings', [{ startDate: '22', { startDate: '23'}] })

Electrograph answered 5/3, 2021 at 7:10 Comment(0)
A
0

fuzes solutions should work nicely,

If you want to attach this newly created instance to source instance then:

const setting = await companies.$create('setting', { startDate: '22' });
companies.set('settings', [...companies.settings, setting]);

Abernathy answered 17/3, 2022 at 13:2 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.