# Repository API

> 英文标题：Repository APIs
> 官网原文：https://typeorm.io/docs/working-with-entity-manager/repository-api
> 文档版本：TypeORM v1.1
> 体例：英文原文（EN）与中文译文（ZH）逐块并列，共 106 块

---

<!-- EN -->
# Repository APIs

<!-- ZH -->
# Repository API

<!-- EN -->
## `Repository` API

<!-- ZH -->
## `Repository` API

<!-- EN -->
* `manager` - The `EntityManager` used by this repository.

<!-- ZH -->
* `manager` - 该 repository 所使用的 `EntityManager`。

<!-- EN -->
```typescript
const manager = repository.manager
```

<!-- ZH -->
```typescript
const manager = repository.manager
```

<!-- EN -->
* `metadata` - The `EntityMetadata` of the entity managed by this repository.

<!-- ZH -->
* `metadata` - 该 repository 所管理实体的 `EntityMetadata`。

<!-- EN -->
```typescript
const metadata = repository.metadata
```

<!-- ZH -->
```typescript
const metadata = repository.metadata
```

<!-- EN -->
* `queryRunner` - The query runner used by `EntityManager`. Used only in transactional instances of EntityManager.

<!-- ZH -->
* `queryRunner` - `EntityManager` 所使用的 query runner。仅在 EntityManager 的事务型实例中使用。

<!-- EN -->
```typescript
const queryRunner = repository.queryRunner
```

<!-- ZH -->
```typescript
const queryRunner = repository.queryRunner
```

<!-- EN -->
* `target` - The target entity class managed by this repository. Used only in transactional instances of EntityManager.

<!-- ZH -->
* `target` - 该 repository 所管理的目标实体类。仅在 EntityManager 的事务型实例中使用。

<!-- EN -->
```typescript
const target = repository.target
```

<!-- ZH -->
```typescript
const target = repository.target
```

<!-- EN -->
* `createQueryBuilder` - Creates a query builder use to build SQL queries. Learn more about [QueryBuilder](https://typeorm.io/docs/query-builder/select-query-builder).

<!-- ZH -->
* `createQueryBuilder` - 创建一个用于构建 SQL 查询的 query builder。进一步了解 [QueryBuilder](https://typeorm.io/docs/query-builder/select-query-builder)。

<!-- EN -->
```typescript
const users = await repository
    .createQueryBuilder("user")
    .where("user.name = :name", { name: "John" })
    .getMany()
```

<!-- ZH -->
```typescript
const users = await repository
    .createQueryBuilder("user")
    .where("user.name = :name", { name: "John" })
    .getMany()
```

<!-- EN -->
* `hasId` - Checks if the given entity's primary column property is defined.

<!-- ZH -->
* `hasId` - 检查给定实体的主键列属性是否已定义。

<!-- EN -->
```typescript
if (repository.hasId(user)) {
    // ... do something
}
```

<!-- ZH -->
```typescript
if (repository.hasId(user)) {
    // ... 做点什么
}
```

<!-- EN -->
* `getId` - Gets the primary column property values of the given entity. If entity has composite primary keys then the returned value will be an object with names and values of primary columns.

<!-- ZH -->
* `getId` - 获取给定实体的主键列属性值。如果实体有复合主键，返回值将是一个包含主键列名称与值的对象。

<!-- EN -->
```typescript
const userId = repository.getId(user) // userId === 1
```

<!-- ZH -->
```typescript
const userId = repository.getId(user) // userId === 1
```

<!-- EN -->
* `create` - Creates a new instance of `User`. Optionally accepts an object literal with user properties which will be written into newly created user object

<!-- ZH -->
* `create` - 创建一个新的 `User` 实例。可选地接受一个带用户属性的对象字面量，这些属性会被写入新建的 user 对象

<!-- EN -->
```typescript
const user = repository.create() // same as const user = new User();
const user = repository.create({
    id: 1,
    firstName: "Timber",
    lastName: "Saw",
}) // same as const user = new User(); user.firstName = "Timber"; user.lastName = "Saw";
```

<!-- ZH -->
```typescript
const user = repository.create() // 等同于 const user = new User();
const user = repository.create({
    id: 1,
    firstName: "Timber",
    lastName: "Saw",
}) // 等同于 const user = new User(); user.firstName = "Timber"; user.lastName = "Saw";
```

<!-- EN -->
* `merge` - Merges multiple entities into a single entity.

<!-- ZH -->
* `merge` - 把多个实体合并进单个实体。

<!-- EN -->
```typescript
const user = new User()
repository.merge(user, { firstName: "Timber" }, { lastName: "Saw" }) // same as user.firstName = "Timber"; user.lastName = "Saw";
```

<!-- ZH -->
```typescript
const user = new User()
repository.merge(user, { firstName: "Timber" }, { lastName: "Saw" }) // 等同于 user.firstName = "Timber"; user.lastName = "Saw";
```

<!-- EN -->
* `preload` - Creates a new entity from the given plain javascript object. If the entity already exists in the database, then it loads it (and everything related to it), replaces all values with the new ones from the given object, and returns the new entity. The new entity is actually an entity loaded from the database with all properties replaced from the new object.

<!-- ZH -->
* `preload` - 从给定的普通 javascript 对象创建一个新实体。如果该实体已存在于数据库中，它会加载它（以及与之相关的一切），用给定对象中的新值替换所有值，并返回这个新实体。这个新实体实际上是从数据库加载而来、其所有属性都被新对象替换后的实体。

<!-- EN -->
  > Note that given entity-like object must have an entity id / primary key to find entity by. Returns undefined if entity with given id was not found.

<!-- ZH -->
  > 注意，给定的类实体对象必须带有实体 id / 主键，以便据此查找实体。如果找不到给定 id 的实体，返回 undefined。

<!-- EN -->
```typescript
const partialUser = {
    id: 1,
    firstName: "Rizzrak",
    profile: {
        id: 1,
    },
}
const user = await repository.preload(partialUser)
// user will contain all missing data from partialUser with partialUser property values:
// { id: 1, firstName: "Rizzrak", lastName: "Saw", profile: { id: 1, ... } }
```

<!-- ZH -->
```typescript
const partialUser = {
    id: 1,
    firstName: "Rizzrak",
    profile: {
        id: 1,
    },
}
const user = await repository.preload(partialUser)
// user 会包含 partialUser 中缺失的所有数据，其中属性值来自 partialUser：
// { id: 1, firstName: "Rizzrak", lastName: "Saw", profile: { id: 1, ... } }
```

<!-- EN -->
* `save` - Saves a given entity or array of entities. If the entity already exist in the database, it is updated. If the entity does not exist in the database, it is inserted. It saves all given entities in a single transaction (in the case of entity, manager is not transactional). Also supports partial updating since all undefined properties are skipped. Returns the saved entity/entities.

<!-- ZH -->
* `save` - 保存给定实体或实体数组。如果实体已存在于数据库中，则更新它。如果实体不存在于数据库中，则插入它。它会在单个事务中保存所有给定实体（在 entity manager 本身不是事务型的情况下）。也支持部分更新，因为所有值为 undefined 的属性都会被跳过。返回被保存的实体。

<!-- EN -->
```typescript
await repository.save(user)
await repository.save([category1, category2, category3])
```

<!-- ZH -->
```typescript
await repository.save(user)
await repository.save([category1, category2, category3])
```

<!-- EN -->
* `remove` - Removes a given entity or array of entities. It removes all given entities in a single transaction (in the case of entity, manager is not transactional). Returns the removed entity/entities.

<!-- ZH -->
* `remove` - 移除给定实体或实体数组。它会在单个事务中移除所有给定实体（在 entity manager 本身不是事务型的情况下）。返回被移除的实体。

<!-- EN -->
```typescript
await repository.remove(user)
await repository.remove([category1, category2, category3])
```

<!-- ZH -->
```typescript
await repository.remove(user)
await repository.remove([category1, category2, category3])
```

<!-- EN -->
* `insert` - Inserts a new entity, or array of entities.

<!-- ZH -->
* `insert` - 插入一个新实体或实体数组。

<!-- EN -->
```typescript
await repository.insert({
    firstName: "Timber",
    lastName: "Timber",
})

await repository.insert([
    {
        firstName: "Foo",
        lastName: "Bar",
    },
    {
        firstName: "Rizz",
        lastName: "Rak",
    },
])
```

<!-- ZH -->
```typescript
await repository.insert({
    firstName: "Timber",
    lastName: "Timber",
})

await repository.insert([
    {
        firstName: "Foo",
        lastName: "Bar",
    },
    {
        firstName: "Rizz",
        lastName: "Rak",
    },
])
```

<!-- EN -->
* `update` - Updates entities by entity id, ids or given conditions. Sets fields from supplied partial entity.

<!-- ZH -->
* `update` - 按实体 id、多个 id 或给定条件更新实体。用提供的部分实体设置字段。

<!-- EN -->
```typescript
await repository.update({ age: 18 }, { category: "ADULT" })
// executes UPDATE user SET category = ADULT WHERE age = 18

await repository.update(1, { firstName: "Rizzrak" })
// executes UPDATE user SET firstName = Rizzrak WHERE id = 1

// optionally request RETURNING / OUTPUT values (supported drivers only)
const result = await repository.update(
    1,
    { firstName: "Rizzrak" },
    { returning: ["id", "firstName"] },
)
console.log(result.raw) // [{ id: 1, firstName: "Rizzrak" }]
```

<!-- ZH -->
```typescript
await repository.update({ age: 18 }, { category: "ADULT" })
// 执行 UPDATE user SET category = ADULT WHERE age = 18

await repository.update(1, { firstName: "Rizzrak" })
// 执行 UPDATE user SET firstName = Rizzrak WHERE id = 1

// 可选地请求 RETURNING / OUTPUT 返回值（仅受支持的驱动）
const result = await repository.update(
    1,
    { firstName: "Rizzrak" },
    { returning: ["id", "firstName"] },
)
console.log(result.raw) // [{ id: 1, firstName: "Rizzrak" }]
```

<!-- EN -->
You can pass an **array of condition objects** to match multiple distinct sets of rows in a single call (conditions are OR'd together):

<!-- ZH -->
你可以传入一个**条件对象数组**，在一次调用中匹配多组不同的行（各条件之间是 OR 关系）：

<!-- EN -->
```typescript
await repository.update([{ status: "expired" }, { flagged: true }], {
    active: false,
})
// executes UPDATE user SET active = false WHERE status = 'expired' OR flagged = true
```

<!-- ZH -->
```typescript
await repository.update([{ status: "expired" }, { flagged: true }], {
    active: false,
})
// 执行 UPDATE user SET active = false WHERE status = 'expired' OR flagged = true
```

<!-- EN -->
* `updateAll` - Updates *all* entities of target type (without WHERE clause). Sets fields from supplied partial entity.

<!-- ZH -->
* `updateAll` - 更新目标类型的*所有*实体（不带 WHERE 子句）。用提供的部分实体设置字段。

<!-- EN -->
```typescript
await repository.updateAll({ category: "ADULT" })
// executes UPDATE user SET category = ADULT

await repository.updateAll(
    { category: "ADULT" },
    { returning: "*" }, // limited to drivers that support returning clauses
)
```

<!-- ZH -->
```typescript
await repository.updateAll({ category: "ADULT" })
// 执行 UPDATE user SET category = ADULT

await repository.updateAll(
    { category: "ADULT" },
    { returning: "*" }, // 仅限支持 returning 子句的驱动
)
```

<!-- EN -->
* `upsert` - Inserts a new entity or array of entities unless they already exist in which case they are updated instead. Supported by AuroraDataApi, Cockroach, Mysql, Postgres, and Sqlite database drivers.

<!-- ZH -->
* `upsert` - 插入一个新实体或实体数组；如果它们已存在，则改为更新。受 AuroraDataApi、Cockroach、Mysql、Postgres 和 Sqlite 数据库驱动支持。

<!-- EN -->
When an upsert operation results in an update (due to a conflict), special columns like `@UpdateDateColumn` and `@VersionColumn` are automatically updated to their current values.

<!-- ZH -->
当 upsert 操作因冲突而变成更新时，`@UpdateDateColumn` 和 `@VersionColumn` 这类特殊列会被自动更新为当前值。

<!-- EN -->
Columns marked with `update: false` or defined as computed generated columns (via `asExpression`/`generatedType`) are **never** included in the update set on conflict. If all non-conflict columns are excluded by these rules (i.e. there are no updatable columns), the upsert degrades to an insert-or-ignore operation and the existing row is left completely unchanged. On databases that support conflict targets (e.g. PostgreSQL, CockroachDB), this is scoped to the specified conflict columns; on MySQL-family databases, `INSERT IGNORE` is used which applies to all unique constraints.

<!-- ZH -->
用 `update: false` 标记的列，或被定义为计算生成列（通过 `asExpression`/`generatedType`）的列，**永远不会**被包含在冲突时的更新集合中。如果所有非冲突列都被这些规则排除（即没有可更新的列），该 upsert 会降级为"插入或忽略"操作，已存在的行保持完全不变。在支持冲突目标的数据库上（例如 PostgreSQL、CockroachDB），这限定在所指定的冲突列范围内；在 MySQL 系数据库上，使用的是 `INSERT IGNORE`，它对所有唯一约束生效。

<!-- EN -->
```typescript
await repository.upsert(
    [
        { externalId: "abc123", firstName: "Rizzrak" },
        { externalId: "bca321", firstName: "Karzzir" },
    ],
    ["externalId"],
)
/** executes
 *  INSERT INTO user
 *  VALUES
 *      (externalId = abc123, firstName = Rizzrak),
 *      (externalId = cba321, firstName = Karzzir),
 *  ON CONFLICT (externalId) DO UPDATE
 *  SET firstName = EXCLUDED.firstName,
 *      updatedDate = CURRENT_TIMESTAMP,
 *      version = version + 1
 **/
```

<!-- ZH -->
```typescript
await repository.upsert(
    [
        { externalId: "abc123", firstName: "Rizzrak" },
        { externalId: "bca321", firstName: "Karzzir" },
    ],
    ["externalId"],
)
/** 执行
 *  INSERT INTO user
 *  VALUES
 *      (externalId = abc123, firstName = Rizzrak),
 *      (externalId = cba321, firstName = Karzzir),
 *  ON CONFLICT (externalId) DO UPDATE
 *  SET firstName = EXCLUDED.firstName,
 *      updatedDate = CURRENT_TIMESTAMP,
 *      version = version + 1
 **/
```

<!-- EN -->
You can also request values to be returned from an upsert (supported on drivers with RETURNING / OUTPUT support):

<!-- ZH -->
你也可以请求从 upsert 中返回值（在支持 RETURNING / OUTPUT 的驱动上可用）：

<!-- EN -->
```typescript
const { raw } = await repository.upsert(
    { externalId: "abc123", firstName: "Rizzrak" },
    {
        conflictPaths: ["externalId"],
        returning: ["externalId", "firstName"],
    },
)
console.log(raw) // [{ externalId: "abc123", firstName: "Rizzrak" }]
```

<!-- ZH -->
```typescript
const { raw } = await repository.upsert(
    { externalId: "abc123", firstName: "Rizzrak" },
    {
        conflictPaths: ["externalId"],
        returning: ["externalId", "firstName"],
    },
)
console.log(raw) // [{ externalId: "abc123", firstName: "Rizzrak" }]
```

<!-- EN -->
```typescript
await repository.upsert(
    [
        { externalId: "abc123", firstName: "Rizzrak" },
        { externalId: "bca321", firstName: "Karzzir" },
    ],
    {
        conflictPaths: ["externalId"],
        skipUpdateIfNoValuesChanged: true, // supported by postgres, skips update if it would not change row values
        upsertType: "upsert", //  "on-conflict-do-update" | "on-duplicate-key-update" | "upsert" - optionally provide an UpsertType - 'upsert' is currently only supported by CockroachDB
    },
)
/** executes
 *  INSERT INTO user
 *  VALUES
 *      (externalId = abc123, firstName = Rizzrak),
 *      (externalId = cba321, firstName = Karzzir),
 *  ON CONFLICT (externalId) DO UPDATE
 *  SET firstName = EXCLUDED.firstName
 *  WHERE user.firstName IS DISTINCT FROM EXCLUDED.firstName
 **/
```

<!-- ZH -->
```typescript
await repository.upsert(
    [
        { externalId: "abc123", firstName: "Rizzrak" },
        { externalId: "bca321", firstName: "Karzzir" },
    ],
    {
        conflictPaths: ["externalId"],
        skipUpdateIfNoValuesChanged: true, // postgres 支持，如果更新不会改变行数据则跳过更新
        upsertType: "upsert", //  "on-conflict-do-update" | "on-duplicate-key-update" | "upsert" —— 可选地指定 UpsertType；'upsert' 目前仅 CockroachDB 支持
    },
)
/** 执行
 *  INSERT INTO user
 *  VALUES
 *      (externalId = abc123, firstName = Rizzrak),
 *      (externalId = cba321, firstName = Karzzir),
 *  ON CONFLICT (externalId) DO UPDATE
 *  SET firstName = EXCLUDED.firstName
 *  WHERE user.firstName IS DISTINCT FROM EXCLUDED.firstName
 **/
```

<!-- EN -->
```typescript
await repository.upsert(
    [
        { externalId: "abc123", firstName: "Rizzrak", dateAdded: "2020-01-01" },
        { externalId: "bca321", firstName: "Karzzir", dateAdded: "2022-01-01" },
    ],
    {
        conflictPaths: ["externalId"],
        skipUpdateIfNoValuesChanged: true, // supported by postgres, skips update if it would not change row values
        indexPredicate: "dateAdded > 2020-01-01", // supported by postgres, allows for partial indexes
    },
)
/** executes
 *  INSERT INTO user
 *  VALUES
 *      (externalId = abc123, firstName = Rizzrak, dateAdded = 2020-01-01),
 *      (externalId = cba321, firstName = Karzzir, dateAdded = 2022-01-01),
 *  ON CONFLICT (externalId) WHERE ( dateAdded > 2021-01-01 ) DO UPDATE
 *  SET firstName = EXCLUDED.firstName,
 *  SET dateAdded = EXCLUDED.dateAdded,
 *  WHERE user.firstName IS DISTINCT FROM EXCLUDED.firstName OR user.dateAdded IS DISTINCT FROM EXCLUDED.dateAdded
 **/
```

<!-- ZH -->
```typescript
await repository.upsert(
    [
        { externalId: "abc123", firstName: "Rizzrak", dateAdded: "2020-01-01" },
        { externalId: "bca321", firstName: "Karzzir", dateAdded: "2022-01-01" },
    ],
    {
        conflictPaths: ["externalId"],
        skipUpdateIfNoValuesChanged: true, // postgres 支持，如果更新不会改变行数据则跳过更新
        indexPredicate: "dateAdded > 2020-01-01", // postgres 支持，允许使用部分索引
    },
)
/** 执行
 *  INSERT INTO user
 *  VALUES
 *      (externalId = abc123, firstName = Rizzrak, dateAdded = 2020-01-01),
 *      (externalId = cba321, firstName = Karzzir, dateAdded = 2022-01-01),
 *  ON CONFLICT (externalId) WHERE ( dateAdded > 2021-01-01 ) DO UPDATE
 *  SET firstName = EXCLUDED.firstName,
 *  SET dateAdded = EXCLUDED.dateAdded,
 *  WHERE user.firstName IS DISTINCT FROM EXCLUDED.firstName OR user.dateAdded IS DISTINCT FROM EXCLUDED.dateAdded
 **/
```

<!-- EN -->
* `delete` - Deletes entities by entity id, ids or given conditions:

<!-- ZH -->
* `delete` - 按实体 id、多个 id 或给定条件删除实体：

<!-- EN -->
```typescript
await repository.delete(1)
await repository.delete([1, 2, 3])
await repository.delete({ firstName: "Timber" })
```

<!-- ZH -->
```typescript
await repository.delete(1)
await repository.delete([1, 2, 3])
await repository.delete({ firstName: "Timber" })
```

<!-- EN -->
* `deleteAll` - Deletes *all* entities of target type (without WHERE clause).

<!-- ZH -->
* `deleteAll` - 删除目标类型的*所有*实体（不带 WHERE 子句）。

<!-- EN -->
```typescript
await repository.deleteAll()
// executes DELETE FROM user
```

<!-- ZH -->
```typescript
await repository.deleteAll()
// 执行 DELETE FROM user
```

<!-- EN -->
Refer also to the `clear` method, which performs database `TRUNCATE TABLE` operation instead.

<!-- ZH -->
另请参阅 `clear` 方法，它执行的是数据库的 `TRUNCATE TABLE` 操作。

<!-- EN -->
* `softDelete` and `restore` - Soft deleting and restoring a row by id, ids, given conditions, or an array of condition objects:

<!-- ZH -->
* `softDelete` 与 `restore` - 按 id、多个 id、给定条件或条件对象数组软删除并恢复一行：

<!-- EN -->
```typescript
const repository = dataSource.getRepository(Entity)
// Soft delete an entity
await repository.softDelete(1)
// And you can restore it using restore;
await repository.restore(1)
// Soft delete multiple entities
await repository.softDelete([1, 2, 3])
// Or soft delete by other attribute
await repository.softDelete({ firstName: "Jake" })

// An array of condition objects is OR'd into one query
await repository.softDelete([{ firstName: "Jake" }, { age: 25 }, { id: 42 }])
// executes UPDATE entity SET deletedAt = NOW() WHERE firstName = Jake OR age = 25 OR id = 42
```

<!-- ZH -->
```typescript
const repository = dataSource.getRepository(Entity)
// 软删除一个实体
await repository.softDelete(1)
// 你可以用 restore 恢复它；
await repository.restore(1)
// 软删除多个实体
await repository.softDelete([1, 2, 3])
// 或者按其他属性软删除
await repository.softDelete({ firstName: "Jake" })

// 条件对象数组会被 OR 组合成一条查询
await repository.softDelete([{ firstName: "Jake" }, { age: 25 }, { id: 42 }])
// 执行 UPDATE entity SET deletedAt = NOW() WHERE firstName = Jake OR age = 25 OR id = 42
```

<!-- EN -->
* `softRemove` and `recover` - This is alternative to `softDelete` and `restore`.

<!-- ZH -->
* `softRemove` 与 `recover` - 这是 `softDelete` 和 `restore` 的替代方案。

<!-- EN -->
```typescript
// You can soft-delete them using softRemove
const entities = await repository.find()
const entitiesAfterSoftRemove = await repository.softRemove(entities)

// And You can recover them using recover;
await repository.recover(entitiesAfterSoftRemove)
```

<!-- ZH -->
```typescript
// 你可以用 softRemove 软删除它们
const entities = await repository.find()
const entitiesAfterSoftRemove = await repository.softRemove(entities)

// 然后你可以用 recover 恢复它们；
await repository.recover(entitiesAfterSoftRemove)
```

<!-- EN -->
* `increment` - Increments some column by provided value of entities that match given options.

<!-- ZH -->
* `increment` - 把匹配给定选项的实体的某个列增加指定值。

<!-- EN -->
```typescript
await repository.increment({ firstName: "Timber" }, "age", 3)
```

<!-- ZH -->
```typescript
await repository.increment({ firstName: "Timber" }, "age", 3)
```

<!-- EN -->
* `decrement` - Decrements some column by provided value that match given options.

<!-- ZH -->
* `decrement` - 把匹配给定选项的某个列减少指定值。

<!-- EN -->
```typescript
await repository.decrement({ firstName: "Timber" }, "age", 3)
```

<!-- ZH -->
```typescript
await repository.decrement({ firstName: "Timber" }, "age", 3)
```

<!-- EN -->
* `exists` - Check whether any entity exists that matches `FindOptions`.

<!-- ZH -->
* `exists` - 检查是否存在匹配 `FindOptions` 的实体。

<!-- EN -->
```typescript
const exists = await repository.exists({
    where: {
        firstName: "Timber",
    },
})
```

<!-- ZH -->
```typescript
const exists = await repository.exists({
    where: {
        firstName: "Timber",
    },
})
```

<!-- EN -->
* `existsBy` - Checks whether any entity exists that matches `FindOptionsWhere`.

<!-- ZH -->
* `existsBy` - 检查是否存在匹配 `FindOptionsWhere` 的实体。

<!-- EN -->
```typescript
const exists = await repository.existsBy({ firstName: "Timber" })
```

<!-- ZH -->
```typescript
const exists = await repository.existsBy({ firstName: "Timber" })
```

<!-- EN -->
* `count` - Counts entities that match `FindOptions`. Useful for pagination.

<!-- ZH -->
* `count` - 统计匹配 `FindOptions` 的实体数量。对分页很有用。

<!-- EN -->
```typescript
const count = await repository.count({
    where: {
        firstName: "Timber",
    },
})

const distinctCount = await repository.count({
    select: {
        firstName: true,
    },
})
```

<!-- ZH -->
```typescript
const count = await repository.count({
    where: {
        firstName: "Timber",
    },
})

const distinctCount = await repository.count({
    select: {
        firstName: true,
    },
})
```

<!-- EN -->
When `select` is provided, counts distinct combinations of selected columns, including selected relation columns when paired with `relations`. If `select` is not provided, default count behavior is unchanged.

<!-- ZH -->
提供了 `select` 时，统计的是所选列的不同组合数量；当与 `relations` 搭配时，也包含所选的关系列。如果未提供 `select`，默认计数行为不变。

<!-- EN -->
* `countBy` - Counts entities that match `FindOptionsWhere`. Useful for pagination.

<!-- ZH -->
* `countBy` - 统计匹配 `FindOptionsWhere` 的实体数量。对分页很有用。

<!-- EN -->
```typescript
const count = await repository.countBy({ firstName: "Timber" })
```

<!-- ZH -->
```typescript
const count = await repository.countBy({ firstName: "Timber" })
```

<!-- EN -->
* `sum` - Returns the sum of a numeric field for all entities that match `FindOptionsWhere`.

<!-- ZH -->
* `sum` - 返回匹配 `FindOptionsWhere` 的所有实体某个数值字段的总和。

<!-- EN -->
```typescript
const sum = await repository.sum("age", { firstName: "Timber" })
```

<!-- ZH -->
```typescript
const sum = await repository.sum("age", { firstName: "Timber" })
```

<!-- EN -->
* `average` - Returns the average of a numeric field for all entities that match `FindOptionsWhere`.

<!-- ZH -->
* `average` - 返回匹配 `FindOptionsWhere` 的所有实体某个数值字段的平均值。

<!-- EN -->
```typescript
const average = await repository.average("age", { firstName: "Timber" })
```

<!-- ZH -->
```typescript
const average = await repository.average("age", { firstName: "Timber" })
```

<!-- EN -->
* `minimum` - Returns the minimum of a numeric field for all entities that match `FindOptionsWhere`.

<!-- ZH -->
* `minimum` - 返回匹配 `FindOptionsWhere` 的所有实体某个数值字段的最小值。

<!-- EN -->
```typescript
const minimum = await repository.minimum("age", { firstName: "Timber" })
```

<!-- ZH -->
```typescript
const minimum = await repository.minimum("age", { firstName: "Timber" })
```

<!-- EN -->
* `maximum` - Returns the maximum of a numeric field for all entities that match `FindOptionsWhere`.

<!-- ZH -->
* `maximum` - 返回匹配 `FindOptionsWhere` 的所有实体某个数值字段的最大值。

<!-- EN -->
```typescript
const maximum = await repository.maximum("age", { firstName: "Timber" })
```

<!-- ZH -->
```typescript
const maximum = await repository.maximum("age", { firstName: "Timber" })
```

<!-- EN -->
* `find` - Finds entities that match given `FindOptions`.

<!-- ZH -->
* `find` - 查找匹配给定 `FindOptions` 的实体。

<!-- EN -->
```typescript
const timbers = await repository.find({
    where: {
        firstName: "Timber",
    },
})
```

<!-- ZH -->
```typescript
const timbers = await repository.find({
    where: {
        firstName: "Timber",
    },
})
```

<!-- EN -->
* `findBy` - Finds entities that match given `FindWhereOptions`.

<!-- ZH -->
* `findBy` - 查找匹配给定 `FindWhereOptions` 的实体。

<!-- EN -->
```typescript
const timbers = await repository.findBy({
    firstName: "Timber",
})
```

<!-- ZH -->
```typescript
const timbers = await repository.findBy({
    firstName: "Timber",
})
```

<!-- EN -->
* `findAndCount` - Finds entities that match given `FindOptions`. Also counts all entities that match given conditions, but ignores pagination settings (from and take options).

<!-- ZH -->
* `findAndCount` - 查找匹配给定 `FindOptions` 的实体。同时统计匹配给定条件的所有实体数量，但会忽略分页设置（from 和 take 选项）。

<!-- EN -->
```typescript
const [timbers, timbersCount] = await repository.findAndCount({
    where: {
        firstName: "Timber",
    },
})
```

<!-- ZH -->
```typescript
const [timbers, timbersCount] = await repository.findAndCount({
    where: {
        firstName: "Timber",
    },
})
```

<!-- EN -->
* `findAndCountBy` - Finds entities that match given `FindOptionsWhere`. Also counts all entities that match given conditions, but ignores pagination settings (from and take options).

<!-- ZH -->
* `findAndCountBy` - 查找匹配给定 `FindOptionsWhere` 的实体。同时统计匹配给定条件的所有实体数量，但会忽略分页设置（from 和 take 选项）。

<!-- EN -->
```typescript
const [timbers, timbersCount] = await repository.findAndCountBy({
    firstName: "Timber",
})
```

<!-- ZH -->
```typescript
const [timbers, timbersCount] = await repository.findAndCountBy({
    firstName: "Timber",
})
```

<!-- EN -->
* `findOne` - Finds the first entity that matches given `FindOptions`.

<!-- ZH -->
* `findOne` - 查找匹配给定 `FindOptions` 的第一个实体。

<!-- EN -->
```typescript
const timber = await repository.findOne({
    where: {
        firstName: "Timber",
    },
})
```

<!-- ZH -->
```typescript
const timber = await repository.findOne({
    where: {
        firstName: "Timber",
    },
})
```

<!-- EN -->
* `findOneBy` - Finds the first entity that matches given `FindOptionsWhere`.

<!-- ZH -->
* `findOneBy` - 查找匹配给定 `FindOptionsWhere` 的第一个实体。

<!-- EN -->
```typescript
const timber = await repository.findOneBy({ firstName: "Timber" })
```

<!-- ZH -->
```typescript
const timber = await repository.findOneBy({ firstName: "Timber" })
```

<!-- EN -->
* `findOneOrFail` - Finds the first entity that matches some id or find options. Rejects the returned promise if nothing matches.

<!-- ZH -->
* `findOneOrFail` - 查找匹配某个 id 或查找选项的第一个实体。如果没有匹配项，返回的 promise 会被拒绝。

<!-- EN -->
```typescript
const timber = await repository.findOneOrFail({
    where: {
        firstName: "Timber",
    },
})
```

<!-- ZH -->
```typescript
const timber = await repository.findOneOrFail({
    where: {
        firstName: "Timber",
    },
})
```

<!-- EN -->
* `findOneByOrFail` - Finds the first entity that matches given `FindOptions`. Rejects the returned promise if nothing matches.

<!-- ZH -->
* `findOneByOrFail` - 查找匹配给定 `FindOptions` 的第一个实体。如果没有匹配项，返回的 promise 会被拒绝。

<!-- EN -->
```typescript
const timber = await repository.findOneByOrFail({ firstName: "Timber" })
```

<!-- ZH -->
```typescript
const timber = await repository.findOneByOrFail({ firstName: "Timber" })
```

<!-- EN -->
* `query` - Executes a raw SQL query.

<!-- ZH -->
* `query` - 执行一条原生 SQL 查询。

<!-- EN -->
```typescript
const rawData = await repository.query(`SELECT * FROM USERS`)

// You can also use parameters to avoid SQL injection
// The syntax differs between the drivers

// aurora-mysql, better-sqlite3, capacitor, cordova,
// expo, mariadb, mysql, nativescript, react-native,
// sap, sqlite, sqljs
const rawData = await repository.query(
    "SELECT * FROM USERS WHERE name = ? and age = ?",
    ["John", 24],
)

// aurora-postgres, cockroachdb, postgres
const rawData = await repository.query(
    "SELECT * FROM USERS WHERE name = $1 and age = $2",
    ["John", 24],
)

// oracle
const rawData = await repository.query(
    "SELECT * FROM USERS WHERE name = :1 and age = :2",
    ["John", 24],
)

// spanner
const rawData = await repository.query(
    "SELECT * FROM USERS WHERE name = @param0 and age = @param1",
    ["John", 24],
)

// mssql
const rawData = await repository.query(
    "SELECT * FROM USERS WHERE name = @0 and age = @1",
    ["John", 24],
)

// mysql2 additionally supports named placeholders
// when extra.namedPlaceholders is true
const rawData = await repository.query(
    "SELECT * FROM USERS WHERE name = :name and age = :age",
    { name: "John", age: 24 },
)
```

<!-- ZH -->
```typescript
const rawData = await repository.query(`SELECT * FROM USERS`)

// 你也可以使用参数来避免 SQL 注入
// 不同驱动的语法有所不同

// aurora-mysql, better-sqlite3, capacitor, cordova,
// expo, mariadb, mysql, nativescript, react-native,
// sap, sqlite, sqljs
const rawData = await repository.query(
    "SELECT * FROM USERS WHERE name = ? and age = ?",
    ["John", 24],
)

// aurora-postgres, cockroachdb, postgres
const rawData = await repository.query(
    "SELECT * FROM USERS WHERE name = $1 and age = $2",
    ["John", 24],
)

// oracle
const rawData = await repository.query(
    "SELECT * FROM USERS WHERE name = :1 and age = :2",
    ["John", 24],
)

// spanner
const rawData = await repository.query(
    "SELECT * FROM USERS WHERE name = @param0 and age = @param1",
    ["John", 24],
)

// mssql
const rawData = await repository.query(
    "SELECT * FROM USERS WHERE name = @0 and age = @1",
    ["John", 24],
)

// 当 extra.namedPlaceholders 为 true 时
// mysql2 还额外支持具名占位符
const rawData = await repository.query(
    "SELECT * FROM USERS WHERE name = :name and age = :age",
    { name: "John", age: 24 },
)
```

<!-- EN -->
* `clear` - Clears all the data from (truncates) the given table. Supports cascade option to also clear all the data from the tables that have foreign keys to this table (supported by PostgreSQL/CockroachDB and Oracle only; other databases throw an error if cascade option is set to true).

<!-- ZH -->
* `clear` - 清空（截断）给定表中的所有数据。支持 cascade 选项，可同时清空带有指向该表外键的表中的所有数据（仅 PostgreSQL/CockroachDB 和 Oracle 支持；其他数据库在 cascade 选项设为 true 时会抛出错误）。

<!-- EN -->
```typescript
await repository.clear()

// With cascade option (PostgreSQL/CockroachDB and Oracle only)
await repository.clear({ cascade: true })
```

<!-- ZH -->
```typescript
await repository.clear()

// 带 cascade 选项（仅 PostgreSQL/CockroachDB 和 Oracle）
await repository.clear({ cascade: true })
```

<!-- EN -->
### Additional Options

<!-- ZH -->
### 额外选项

<!-- EN -->
Optional `SaveOptions` can be passed as parameter for `save`.

<!-- ZH -->
可以给 `save` 传入可选的 `SaveOptions` 参数。

<!-- EN -->
* `data` - Additional data to be passed with persist method. This data can be used in subscribers then.
* `listeners`: boolean - Indicates if listeners and subscribers are called for this operation. By default they are enabled, you can disable them by setting `{ listeners: false }` in save/remove options.
* `transaction`: boolean - By default transactions are enabled and all queries in persistence operation are wrapped into the transaction. You can disable this behaviour by setting `{ transaction: false }` in the persistence options.
* `chunk`: number - Breaks save execution into multiple groups of chunks. For example, if you want to save 100.000 objects but you have issues with saving them, you can break them into 10 groups of 10.000 objects (by setting `{ chunk: 10000 }`) and save each group separately. This option is needed to perform very big insertions when you have issues with underlying driver parameter number limitation.
* `reload`: boolean - Flag to determine whether the entity that is being persisted should be reloaded during the persistence operation. It will work only on databases which do not support RETURNING / OUTPUT statement. Enabled by default.

<!-- ZH -->
* `data` - 随持久化方法一起传递的额外数据。这些数据之后可以在订阅者中使用。
* `listeners`: boolean - 表示本次操作是否调用监听器和订阅者。默认是启用的，你可以在 save/remove 选项中设置 `{ listeners: false }` 来禁用它们。
* `transaction`: boolean - 默认情况下事务是启用的，持久化操作中的所有查询都会被包在事务里。你可以在持久化选项中设置 `{ transaction: false }` 来禁用这一行为。
* `chunk`: number - 把保存操作拆成多个分组块。例如，如果你想保存 100.000 个对象但遇到了问题，可以把它们拆成 10 组、每组 10.000 个对象（设置 `{ chunk: 10000 }`），然后分别保存每一组。当你受限于底层驱动的参数数量上限而无法完成超大批量插入时，需要用到该选项。
* `reload`: boolean - 决定被持久化的实体是否应在持久化操作期间重新加载。它只在不支持 RETURNING / OUTPUT 语句的数据库上生效。默认启用。

<!-- EN -->
Example:

<!-- ZH -->
示例：

<!-- EN -->
```typescript
userRepository.save(users, { chunk: 1000 })
```

<!-- ZH -->
```typescript
userRepository.save(users, { chunk: 1000 })
```

<!-- EN -->
Optional `RemoveOptions` can be passed as parameter for `remove` and `delete`.

<!-- ZH -->
可以给 `remove` 和 `delete` 传入可选的 `RemoveOptions` 参数。

<!-- EN -->
* `data` - Additional data to be passed with remove method. This data can be used in subscribers then.
* `listeners`: boolean - Indicates if listeners and subscribers are called for this operation. By default they are enabled, you can disable them by setting `{ listeners: false }` in save/remove options.
* `transaction`: boolean - By default transactions are enabled and all queries in persistence operation are wrapped into the transaction. You can disable this behaviour by setting `{ transaction: false }` in the persistence options.
* `chunk`: number - Breaks removal execution into multiple groups of chunks. For example, if you want to remove 100.000 objects but you have issues doing so, you can break them into 10 groups of 10.000 objects, by setting `{ chunk: 10000 }`, and remove each group separately. This option is needed to perform very big deletions when you have issues with underlying driver parameter number limitation.

<!-- ZH -->
* `data` - 随 remove 方法一起传递的额外数据。这些数据之后可以在订阅者中使用。
* `listeners`: boolean - 表示本次操作是否调用监听器和订阅者。默认是启用的，你可以在 save/remove 选项中设置 `{ listeners: false }` 来禁用它们。
* `transaction`: boolean - 默认情况下事务是启用的，持久化操作中的所有查询都会被包在事务里。你可以在持久化选项中设置 `{ transaction: false }` 来禁用这一行为。
* `chunk`: number - 把移除操作拆成多个分组块。例如，如果你想移除 100.000 个对象但遇到了问题，可以把它们拆成 10 组、每组 10.000 个对象（设置 `{ chunk: 10000 }`），然后分别移除每一组。当你受限于底层驱动的参数数量上限而无法完成超大批量删除时，需要用到该选项。

<!-- EN -->
Example:

<!-- ZH -->
示例：

<!-- EN -->
```typescript
userRepository.remove(users, { chunk: 1000 })
```

<!-- ZH -->
```typescript
userRepository.remove(users, { chunk: 1000 })
```

<!-- EN -->
## `TreeRepository` API

<!-- ZH -->
## `TreeRepository` API

<!-- EN -->
For `TreeRepository` API refer to [the Tree Entities documentation](https://typeorm.io/docs/entity/tree-entities#working-with-tree-entities).

<!-- ZH -->
关于 `TreeRepository` API，请参阅[树形实体文档](https://typeorm.io/docs/entity/tree-entities#working-with-tree-entities)。

<!-- EN -->
## `MongoRepository` API

<!-- ZH -->
## `MongoRepository` API

<!-- EN -->
For `MongoRepository` API refer to [the MongoDB documentation](https://typeorm.io/docs/drivers/mongodb).

<!-- ZH -->
关于 `MongoRepository` API，请参阅 [MongoDB 文档](https://typeorm.io/docs/drivers/mongodb)。
