【问题标题】:TypeORM updating entity/tableTypeORM 更新实体/表
【发布时间】:2018-09-10 18:31:59
【问题描述】:

这是我的用户实体:

@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[];

这是我要更新的新数据:

User {
  userName: 'qweret@gmail.com',
  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' } }

我正在按用户 ID 搜索用户。

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

上面的查询给了我结果:

User {
  createdDate: 2018-03-29T06:45:16.322Z,
  updatedDate: 2018-04-01T06:28:24.171Z,
  userId: 1,
  userName: 'qweret@gmail.com' }

我想更新我的用户表及其相关表

manager.save(user)

将在表中插入新行,而不是更新现有行。有没有办法在不手动更新每一列的情况下更新整个用户表及其相关表? 我不想像这样执行这个任务:

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.

【问题讨论】:

  • 您好,您找到解决问题的方法了吗?
  • 更新方法需要一个查找条件(可以是 id),所以它现在可以更新哪一行

标签: mysql node.js database typeorm


【解决方案1】:

试试这个方法:

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

const updatedUser = await this.repository.findOne(user.id);            

【讨论】:

    猜你喜欢
    • 2022-06-14
    • 2022-06-14
    • 2021-08-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-05
    • 2019-09-01
    • 2020-10-18
    • 2021-07-16
    相关资源
    最近更新 更多