I have two entities (tables): users and roles. There is a many-to-one relation between both entities (a user can have one role, roles can be related to many users). Now I want to update the user entity (which can also include an update of the user's role) by excuting following commands:
const user = await this.userRepository.preload(partialUser);
await this.userRepository.save(user);
return user;
partialUser
(user properties to update) is merged with user data from database including role
user
(merged object) is saved to databaserole
is not loaded (but if I add a child property role
to partialUser
, it's okay)user
(merged object) is saved to database (also with role
, if it was part of partialUser
)Why is role
not loaded via preload
nor return
after save
? Are TypeORM repositories not well made for relations or do I use it incorrectly?
At the moment I have to read the whole user
entity again after saving it, so that the full object (including role
relation) can be returned to the caller. I think thats not very efficient. Is it intended that way?
const user = await this.userRepository.preload(partialUser);
await this.userRepository.save(user);
return this.userRepository.findOne({
where: { id: user.id },
relations: ['role']
});
TypeORM has support for such use-cases. It's done using the eager-loading flag i.e. eager: true
that you can set to the relation. Now everytime you fetch this record, the relation will be fetched by default and returned in the response. Example code that you can use in User model:
@ManyToMany(type => Role, role => role.User, {
eager: true
})
public roles: Role[];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With