Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeORM updating entity/table

This is my User entity:

@PrimaryGeneratedColumn()
userId: number;

@Column({type:"varchar", length:"300"})
userName: string;

@OneToOne(type => UserProfile, {cascadeAll:true})
@JoinColumn()
userProfile: UserProfile;

@OneToOne(type => UserCredential, {cascadeAll:true, eager:true})
@JoinColumn()
userCredential: UserCredential;

@OneToOne(type => BusinessUnit, {cascadeAll:true})
@JoinColumn()
businessUnit: BusinessUnit;

@ManyToMany(type => ProductCategory)
@JoinTable()
productCategory: ProductCategory[];

and this is my new data which i want to update:

User {
  userName: '[email protected]',
  userProfile: 
   UserProfile {
     firstName: 'dcds',
     lastName: 'Faiz',
     mobile: '42423423',
     addressLine1: 'Delhi',
     addressLine2: 'Delhi',
     city: '-',
     country: '-',
     zipCode: '234243',
     homeTelephone: '-',
     dayOfBirth: 0,
     monthOfBirth: 0,
     yearOfBirth: 0 },
  userCredential: UserCredential { credential: 'abcd@123' } }

i'm searching user by its userId.

return await getManager()
               .createQueryBuilder(User, "user")
               .where("user.userId = :id", {id})
               .getOne();

the above query gives me result:

User {
  createdDate: 2018-03-29T06:45:16.322Z,
  updatedDate: 2018-04-01T06:28:24.171Z,
  userId: 1,
  userName: '[email protected]' }

i want to update my user table and its related tables

manager.save(user)

will insert a new row in the table instead of updating the existing the row. Is there a way to update the whole user table and its related table without updating every column manually? i don't want to perform this task like this:

let user = await userRepositiory.findOneById(1);
user.userName = "Me, my friends and polar bears";
await userRepository.save(user);

let userProfile = await userProfileRepository.findOneById(1);
 userProfile.firstName = "";
 userProfile.lastName = "";
    ....// etc
 await userRepository.save(userProfile);

 // and so on update other tables.
like image 258
Aarush Aaditya Avatar asked Apr 01 '18 08:04

Aarush Aaditya


1 Answers

Try this method:

await this. userRepository.update(
                user.id ,
                user
              );

const updatedUser = await this.repository.findOne(user.id);            
like image 52
Bary Levy Avatar answered Oct 31 '22 10:10

Bary Levy