Reputation: 121
I have the following two entities with a OneToMany/ManyToOne relation between them:
@Entity({ name: 'user' })
export class User {
@PrimaryGeneratedColumn('increment')
id: number;
@Column({ type: 'varchar' })
firstName: string;
@Column({ type: 'varchar' })
lastName: string;
@ManyToOne(() => Group, group => group.id)
@JoinColumn({ name: 'groupId' })
group: Group;
@Column({ type: 'integer' })
groupId: number;
}
@Entity({ name: 'group' })
export class Group {
@PrimaryGeneratedColumn('increment')
id: number;
@Column({ type: 'varchar' })
name: string;
@OneToMany(() => User, user => user.group)
members: User[];
}
When I create a new group in my Group repository, I can add existing members as follows:
const group = new Group();
group.name = 'Test';
group.members = [{ id: 1 }, { id: 2 }]; // user ids
this.save(group);
I am wondering if I can update existing members in a similar way. For example if a group with id 1 has two members:
{ id: 1, firstName: 'Member', lastName: 'One', groupId: 1 }
{ id: 2, firstName: 'Member', lastName: 'Two', groupId: 1 }
Is it possible to update a member through the OneToMany relation in a similar way as I'm adding them ? Something like (making this up):
const group = await repository.findOne(groupId, { relations: ['members'] });
group.members = [{ id: 1, firstName: 'Updated' }]; // this would update the firstName of member with id 1 if it exists in the relation
repository.save(group);
Thanks!
Upvotes: 3
Views: 11626
Reputation: 41
There is no built in functionality in typeorm to update specific related entity from the base entity. However if you want to do this then you can add a general function which updates the base table as well as it's relations.
Upvotes: 4