企业🤖AI智能体构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
[TOC] ## 查询 **简单查询** ``` const firstUser = await dataSource .getRepository(User) .createQueryBuilder("user") .where("user.id = :id", { id: 1 }) .getOne() ``` **创建和使用QueryBuilder** ``` const user = await dataSource.manager .createQueryBuilder(User, "user") .where("user.id = :id", { id: 1 }) .getOne() ``` ## 插入 批量插入 ``` await dataSource .createQueryBuilder() .insert() .into(User) .values([ { firstName: "Timber", lastName: "Saw" }, { firstName: "Phantom", lastName: "Lancer" }, ]) .execute() ``` 就性能而言,这是将行插入数据库的最有效方式。您也可以通过这种方式执行批量插入。 支持原生 ``` await dataSource .createQueryBuilder() .insert() .into(User) .values({ firstName: "Timber", lastName: () => "CONCAT('S', 'A', 'W')", }) .execute() ``` ## 更新 ``` await dataSource .createQueryBuilder() .update(User) .set({ firstName: "Timber", lastName: "Saw" }) .where("id = :id", { id: 1 }) .execute() ``` ## 删除 ``` await dataSource .createQueryBuilder() .delete() .from(User) .where("id = :id", { id: 1 }) .execute() ``` ## where ``` orWhere andWhere where ``` ## ORDER BY ``` createQueryBuilder("user").orderBy("user.id") ``` ## GROUP BY ``` createQueryBuilder("user").groupBy("user.id") ``` ## 分页 ``` const users = await dataSource .getRepository(User) .createQueryBuilder("user") .leftJoinAndSelect("user.photos", "photo") .skip(5) .take(10) .getMany() ``` ## 打印sql 返回sql ``` const sql = createQueryBuilder("user") .where("user.firstName = :firstName", { firstName: "Timber" }) .orWhere("user.lastName = :lastName", { lastName: "Saw" }) .getSql() ``` 打印控制台 ``` const users = await createQueryBuilder("user") .where("user.firstName = :firstName", { firstName: "Timber" }) .orWhere("user.lastName = :lastName", { lastName: "Saw" }) .printSql() .getMany() ``` ## 缓存查询 您可以缓存通过以下方法选择的结果`QueryBuilder`:`getMany`、`getOne`、`getRawMany`和。`getRawOne``getCount` 您还可以缓存由and的`find*`和`count*`方法选择的结果。`Repository``EntityManager` 要启用缓存,现在数据 ``` { type: "mysql", host: "localhost", username: "test", ... cache: true } ``` 缓存 ``` const users = await dataSource .createQueryBuilder(User, "user") .where("user.isAdmin = :isAdmin", { isAdmin: true }) .cache(true) .getMany() ```