TypeORM 有哪几种修改数据的方式

TypeORM 提供了多种修改数据的方式,下面是其中几种常用的方式:

使用 save() 方法修改实体对象:通过修改实体对象的属性值并调用 save() 方法,可以将修改后的数据保存回数据库中。例如:

const personRepository = getRepository(Person);
const person = await personRepository.findOne(1);
person.name = 'Alice';
person.age = 30;
await personRepository.save(person);

使用 createQueryBuilder() 构建查询并调用 update() 方法修改数据:使用 createQueryBuilder() 构建查询对象,并调用 update() 方法来执行更新操作。例如:

const personRepository = getRepository(Person);
await personRepository.createQueryBuilder()
  .update(Person)
  .set({ name: 'Alice', age: 30 })
  .where('id = :id', { id: 1 })
  .execute();

使用 update() 方法修改实体对象:使用 update() 方法更新指定实体对象的属性值。例如:

const personRepository = getRepository(Person);
await personRepository.update(1, { name: 'Alice', age: 30 });

使用原生 SQL 修改数据:通过 query() 方法执行原生 SQL 语句来更新数据库中的数据。例如:

const personRepository = getRepository(Person);
await personRepository.query('UPDATE person SET name = ?, age = ? WHERE id = ?', ['Alice', 30, 1]);

需要注意的是,以上方式中的每种方式都有其适用的场景和注意事项,具体使用哪种方式需要根据具体情况进行选择。例如,如果只需要更新一个实体对象的几个属性,使用 save() 方法是比较简单和方便的;如果需要更新符合条件的多个实体对象的属性,使用 createQueryBuilder() 或 update() 方法会更加高效;如果需要执行复杂的更新操作,使用原生 SQL 可能会更加灵活。