Repository navigation
Closed
Description
With the following models & associations, how can I perform an update with this JSON?
I've spent a day trying to do this and don't know why I can't figure it out!
{
"firstName": "firstName1",
"lastName": "lastName1",
"company": "company1",
"email": "email1",
"isActive": false,
"notes": "notes1",
"addresses": [{
"street": "street1",
"city": "city1",
"country": "country1",
"region": "region1",
"postalCode": "postalCode1"
},
{
"street": "street2",
"city": "city2",
"country": "country2",
"region": "region2",
"postalCode": "postalCode2"
}],
"phones": [{
"number": 1234,
"extension": 1234,
"type": "Cell"
},
{
"number": 1234,
"extension": 1234,
"type": "Home"
}]
}import { Table, Column, Model, HasOne, HasMany } from 'sequelize-typescript';
import Address from './address.model';
import Phone from './phone.model';
@Table({
tableName: 'customer',
timestamps: true
})
export default class Customer extends Model<Customer> {
@Column company: string;
@Column email: string;
@Column firstName: string;
@Column isActive: boolean;
@Column lastName: string;
@Column notes: string;
@HasMany(() => Address, { onDelete: 'cascade' }) addresses: Address[];
@HasMany(() => Phone, { onDelete: 'cascade' }) phones: Phone[];
}import { Table, Column, Model, ForeignKey, BelongsTo } from 'sequelize-typescript';
import Customer from './customer.model';
@Table({
tableName: 'address',
timestamps: true
})
export default class Address extends Model<Address> {
@Column street: string;
@Column city: string;
@Column country: string;
@Column region: string;
@Column postalCode: string;
@ForeignKey(() => Customer)
@Column customerId: number;
@BelongsTo(() => Customer, { onDelete: 'cascade' })
customer: Customer;
}import { Table, Column, Default, DataType, Model, BelongsTo, ForeignKey } from 'sequelize-typescript';
import Customer from './customer.model';
@Table({
tableName: 'phone',
timestamps: true
})
export default class Phone extends Model<Phone> {
@Column number: string;
@Column extension?: number;
@Column type: string;
@ForeignKey(() => Customer)
@Column customerId: number;
@BelongsTo(() => Customer, { onDelete: 'cascade' })
customer: Customer;
}Metadata
Metadata
Assignees
Labels
No labels
Activity
RobinBuschmann commentedon Feb 21, 2018
Hey @doovers did you this example: https://stackoverflow.com/questions/33918383/sequelize-update-with-association
Regarding this issue sequelize/sequelize#7703, this feature doesn't seem to be implemented with
Model.updatedoovers commentedon Feb 21, 2018
@RobinBuschmann Yes I saw that post. I have been successful in updating a
HasOneassociation like this:But my customer model has
HasManyassociations for phone and address so I'm unsure how to do this. My goal is that the array of addresses and phones is updated with the customer object.RobinBuschmann commentedon Feb 21, 2018
Unfortunately you will need to do it manually. Ideally within a db transaction(?)
doovers commentedon Feb 21, 2018
@RobinBuschmann Is it a case of deleting the existing address and phone objects and adding the new? Do you have an example of how to do this?
MaheshCasiraghi commentedon Mar 8, 2018
@doovers your code actually builds and inserts a new record into db. It kind of works, but leaves back old instances of associated models, now no longer associated. Here an example of how to make it working, assuming User has a hasOne relationship with Country:
First export the Providers and import them in modules:
export const usersProviders = [ { provide: 'UsersRepository', useValue: User, }, ];export const countriesProviders = [ { provide: 'CountriesRepository', useValue: Country, }, ];then inject Repositories them into service:
@Inject('UsersRepository') public readonly usersRepository: typeof Model, @Inject('CountriesRepository') public readonly countriesRepository: typeof Model,and then you can run:
this.countriesRepository.update({"countryAttribute" : "countryValue"}, {where: {userId: id}});which updates your associated model, without creating an new record.
If something structure-wise is not clear in my example, refer to this: https://docs.nestjs.com/recipes/sql-sequelize
doovers commentedon Mar 14, 2018
@MaheshCasiraghi I think I'm achieving the same thing with this code for a
HasOne:But how would I achieve something similar for a
HasMany? This is my current approach:@RobinBuschmann Is the above equivalent to what you were suggesting regarding the transactions?
RobinBuschmann commentedon Mar 15, 2018
@doovers What I mean with transactions are db transactions. See http://docs.sequelizejs.com/manual/tutorial/transactions.html
MikeDabrowski commentedon Mar 18, 2018
Do I understand it correctly: in order to update associated entities I need to remove them and use create to add them back?
RobinBuschmann commentedon Mar 18, 2018
@MikeDabrowski No, this is not necessary.
@doovers & @MikeDabrowski What about this:
The
reqobject is more or less pseudo code based onexpress.(I haven't tested it yet)
Update: Notice, if needed, a deletion of removed addresses or phones could be implemented as well.
doovers commentedon Mar 22, 2018
@RobinBuschmann Nice, thanks for that. I now have a working solution:
mschipperheyn commentedon Jul 20, 2018
@doovers nice. But you should not put
await customer.$createetc. That kills the parallel behavior ofPromise.all. It should imho beblankstar85 commentedon Dec 19, 2018
I figured out an error in my code, i was defining the HasMany with an array HasMany .... model[].
Once I did that, the functions i was looking for finally showed in my ide,
So now i'm just trying to figure out the typing in the get delta function and where/how Delta is defined. Thanks!