使用 QueryBuilder

你可以使用 QueryBuilder 构建几乎任何复杂性的 SQL 查询。例如,可以这样做:

  1. let photos = await connection
  2. .getRepository(Photo)
  3. .createQueryBuilder("photo") // first argument is an alias. Alias is what you are selecting - photos. You must specify it.
  4. .innerJoinAndSelect("photo.metadata", "metadata")
  5. .leftJoinAndSelect("photo.albums", "album")
  6. .where("photo.isPublished = true")
  7. .andWhere("(photo.name = :photoName OR photo.name = :bearName)")
  8. .orderBy("photo.id", "DESC")
  9. .skip(5)
  10. .take(10)
  11. .setParameters({ photoName: "My", bearName: "Mishka" })
  12. .getMany();

此查询选择所有 published 的 name 等于”My”或”Mishka”的 photos。它将从结果中的第 5 个(分页偏移)开始,并且仅选择 10 个结果(分页限制)。得到的结果将按 ID 降序排序。photo 的 albums 将被 left-joined,其元数据将被 inner joined。

由于 QueryBuilder 的自由度更高,因此在项目中可能会大量的使用它。更多关于 QueryBuilder 的信息,可查看