TypeOrm doesn't save entity with it's relation on update
13,421
The cascade should be set. Here is an example of mine entities:
@Entity()
@Index([ 'studyId', 'teamId', 'enterdate' ])
export class DataMessage extends BaseEntity {
@PrimaryGeneratedColumn('increment') id: number;
@CreateDateColumn() enterdate: Date;
@UpdateDateColumn({ select: false })
updatedAt?: Date;
@Column() owner: string;
@Column() studyId: number;
@Column() teamId: number;
@Column() patient: string;
@Column() orderId: number;
@Column({ default: DataMessageStatus.OPEN })
status: DataMessageStatus;
@Column()
@Index()
resultId: number;
@OneToMany(() => DataMessageContent, (c) => c.message, { cascade: true })
contents: DataMessageContent[];
}
@Entity()
export class DataMessageContent extends BaseEntity {
@PrimaryGeneratedColumn('increment') id: number;
@CreateDateColumn() enterdate: Date;
@Column() owner: string;
@Column() role: UserRole;
@Column({ default: MessageStatus.UNREAD })
status: MessageStatus;
@Column() txt: string;
@ManyToOne(() => DataMessage, (m) => m.contents)
message: DataMessage;
}
This should also work for onetoone relation as well.
Author by
Ben Beri
Updated on June 13, 2022Comments
-
Ben Beri almost 2 years
Given the following relation:
@Entity({name: 'accounts'}) export class Account { @PrimaryGeneratedColumn('uuid') id: string; @OneToOne(type => Address, address => address.id) @JoinColumn({name: 'address_id'}) address: Address; @Column() name: string; }
And the addres relation:
@Entity({name: 'addresses'}) export class Address { @PrimaryGeneratedColumn('uuid') id: string; @Column({length: 45}) country: string; }
When I get the
account
entity by this:/** * Gets account by haccount ID with ALL relations * @param accountId The account ID */ public async getAccountByAccountIdWithRelations(accountId: string): Promise<Account> { return await this.findOneOrFail({id: accountId}, {relations: ['address']}); }
I get the full
Account
entity with theAddress
relation in it.And then when I do the following:
account.address.country = 'newcountry';
and do
this.save(account)
inaccountRepository
the address won't update at all!When I do console log before the save, I see the
account
entity with the updated address, so this is something really strange!Why is it happening?
Note: All queries are done in a transaction; I dont know if it matters
-
atymic over 4 yearsCan you add some more context around your answer?
-
tano over 4 yearsI've added a complete example
-
Ben Beri over 4 yearsThat's right, cascade makes it delete and save recursive, thanks!