TypeORM 查询数据方式有几种

TypeORM 支持多种查询方式,可以根据不同的需求使用不同的查询方式。常见的查询方式包括:

使用实体对象的 Repository 进行查询,例如:

const userRepository = getRepository(User);
const users = await userRepository.find();

使用 QueryBuilder 进行查询,QueryBuilder 提供了更灵活的查询方式,可以根据不同的条件组装 SQL 语句,例如:

const users = await getRepository(User)
  .createQueryBuilder("user")
  .where("user.firstName = :firstName", { firstName: "John" })
  .orWhere("user.lastName = :lastName", { lastName: "Doe" })
  .getMany();

使用原生 SQL 进行查询,可以使用 EntityManager 的 query 方法执行原生 SQL 查询,例如:
typescript
Copy code

const users = await entityManager.query("SELECT * FROM users WHERE firstName = 'John'");

使用 findAndCount 方法查询数据及总条数,例如:

const [users, count] = await userRepository.findAndCount();

使用 findAndCount 方法查询数据及总条数,并支持分页查询,例如:

const [users, count] = await userRepository.findAndCount({
  skip: 10,
  take: 10,
});

使用 find 方法根据条件查询数据,例如:

const users = await userRepository.find({
  where: {
    firstName: "John",
    lastName: "Doe",
  },
  order: {
    firstName: "ASC",
    lastName: "DESC",
  },
  take: 10,
  skip: 10,
});

使用 findOne 方法查询单条数据,例如:

const user = await userRepository.findOne({
  where: {
    id: 1,
  },
  relations: ["posts"],
});

以上是常见的查询方式,根据具体的业务需求选择合适的查询方式即可。