Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeORM: Updating data (with relations) via Repository API

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;

Expected behavior

  1. partialUser (user properties to update) is merged with user data from database including role
  2. user (merged object) is saved to database
  3. new user object is returned to caller (including role)

What happens

  1. user is merged, but role is not loaded (but if I add a child property role to partialUser, it's okay)
  2. user (merged object) is saved to database (also with role, if it was part of partialUser)
  3. new user object is returned, but it's missing role, if role was not updated via partialUser

Question

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?

My workaround

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']
});
like image 575
cvhberger Avatar asked Oct 20 '18 10:10

cvhberger


1 Answers

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[];
like image 175
VPaul Avatar answered Sep 21 '22 14:09

VPaul