'how to create association instance from source instance with sequelize-typescript
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 ?
Solution 1:[1]
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'}] })
Solution 2:[2]
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]);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | fuzes |
| Solution 2 | Hendrik Asso |
