Update collection.md

This commit is contained in:
Pearl C 2023-01-15 22:20:12 +08:00 committed by GitHub
parent 5a938bf3bd
commit f6bc966c20
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -1,28 +1,27 @@
# Collection # Collection
## 概览 ## Overview
`Collection` 用于定义系统中的数据模型,如模型名称、字段、索引、关联等信息。 `Collection` is used to define the data model in the system, such as model name, fields, indexes, associations and other information. It is usually called through the `collection` method of the `Database` instance as a proxy entry.
一般通过 `Database` 实例的 `collection` 方法作为代理入口调用。
```javascript ```javascript
const { Database } = require('@nocobase/database') const { Database } = require('@nocobase/database')
// 创建数据库实例 // Create database instance
const db = new Database({...}); const db = new Database({...});
// 定义数据模型 // Define data model
db.collection({ db.collection({
name: 'users', name: 'users',
// 定义模型字段 // Define model fields
fields: [ fields: [
// 标量字段 // Scalar field
{ {
name: 'name', name: 'name',
type: 'string', type: 'string',
}, },
// 关联字段 // Association field
{ {
name: 'profile', name: 'profile',
type: 'hasOne' // 'hasMany', 'belongsTo', 'belongsToMany' type: 'hasOne' // 'hasMany', 'belongsTo', 'belongsToMany'
@ -31,30 +30,30 @@ db.collection({
}); });
``` ```
更多字段类型请参考 [Fields](/api/database/field.md)。 Refer to [Fields](/api/database/field.md) for more field types.
## 构造函数 ## Constructor
**签名** **Signature**
* `constructor(options: CollectionOptions, context: CollectionContext)` * `constructor(options: CollectionOptions, context: CollectionContext)`
**参数** **Parameter**
| 参数名 | 类型 | 默认值 | 描述 | | Name | Type | Default | Description |
| --- | --- | --- | --- | | --- | --- | --- | --- |
| `options.name` | `string` | - | collection 标识 | | `options.name` | `string` | - | collection identifier |
| `options.tableName?` | `string` | - | 数据库表名,如不传则使用 `options.name` 的值 | | `options.tableName?` | `string` | - | Database table name, the value of `options.name` is used if not set |
| `options.fields?` | `FieldOptions[]` | - | 字段定义,详见 [Field](./field) | | `options.fields?` | `FieldOptions[]` | - | Definition of fields, refer to [Field](./field) for details |
| `options.model?` | `string \| ModelStatic<Model>` | - | Sequelize 的 Model 类型,如果使用的是 `string`,则需要调用之前在 db 上注册过该模型名称 | | `options.model?` | `string \| ModelStatic<Model>` | - | Model type of Sequelize; in case `string` is used, this model name needs to be registered in the db before being called |
| `options.repository?` | `string \| RepositoryType` | - | 数据仓库类型,如果使用 `string`,则需要调用之前在 db 上注册过该仓库类型 | | `options.repository?` | `string \| RepositoryType` | - | Data repository type; in case `string` is used, this repository type needs to be registered in the db before being called |
| `options.sortable?` | `string \| boolean \| { name?: string; scopeKey?: string }` | - | 数据可排序字段配置,默认不排序 | | `options.sortable?` | `string \| boolean \| { name?: string; scopeKey?: string }` | - | Configure which fields are sortable ; not sortable by default |
| `options.autoGenId?` | `boolean` | `true` | 是否自动生成唯一主键,默认为 `true` | | `options.autoGenId?` | `boolean` | `true` | Whether to automatically generate unique primary key; `true` by default |
| `context.database` | `Database` | - | 所在的上下文环境数据库 | | `context.database` | `Database` | - | The context database in which it resides |
**示例** **Example**
创建一张文章表: Create a table <i>posts</i>:
```ts ```ts
const posts = new Collection({ const posts = new Collection({
@ -70,62 +69,62 @@ const posts = new Collection({
} }
] ]
}, { }, {
// 已存在的数据库实例 // An existing database instance
database: db database: db
}); });
``` ```
## 实例成员 ## Instance Member
### `options` ### `options`
数据表配置初始参数。与构造函数的 `options` 参数一致。 Initial parameters for data table configuration, which are consistent with the `options` parameter of the constructor.
### `context` ### `context`
当前数据表所属的上下文环境,目前主要是数据库实例。 The contextual environment to which the current data table belongs, currently mainly the database instance.
### `name` ### `name`
数据表名称。 Name of the data table.
### `db` ### `db`
所属数据库实例。 The database instance to which it belongs.
### `filterTargetKey` ### `filterTargetKey`
作为主键的字段名。 Name of the field that is used as the primary key.
### `isThrough` ### `isThrough`
是否为中间表。 Whether it is an intermediate table.
### `model` ### `model`
匹配 Sequelize 的 Model 类型。 Match the Model type of Sequelize.
### `repository` ### `repository`
数据仓库实例。 Data repository instance.
## 字段配置方法 ## 字段配置方法
### `getField()` ### `getField()`
获取数据表已定义对应名称的字段对象。 Get a field object whose corresponding name has been defined in the data table.
**签名** **Signature**
* `getField(name: string): Field` * `getField(name: string): Field`
**参数** **Parameter**
| 参数名 | 类型 | 默认值 | 描述 | | Name | Type | Default | Description |
| --- | --- | --- | --- | | --- | --- | --- | --- |
| `name` | `string` | - | 字段名称 | | `name` | `string` | - | Name of the field |
**示例** **Example**
```ts ```ts
const posts = db.collection({ const posts = db.collection({
@ -143,20 +142,20 @@ const field = posts.getField('title');
### `setField()` ### `setField()`
对数据表设置字段。 Set a field to the data table.
**签名** **Signature**
* `setField(name: string, options: FieldOptions): Field` * `setField(name: string, options: FieldOptions): Field`
**参数** **Parameter**
| 参数名 | 类型 | 默认值 | 描述 | | Name | Type | Default | Description |
| --- | --- | --- | --- | | --- | --- | --- | --- |
| `name` | `string` | - | 字段名称 | | `name` | `string` | - | Name of the field |
| `options` | `FieldOptions` | - | 字段配置,详见 [Field](./field) | | `options` | `FieldOptions` | - | Configuration of the field, refer to [Field](./field) for details |
**示例** **Example**
```ts ```ts
const posts = db.collection({ name: 'posts' }); const posts = db.collection({ name: 'posts' });
@ -166,20 +165,20 @@ posts.setField('title', { type: 'string' });
### `setFields()` ### `setFields()`
对数据表批量设置多个字段。 Set multiple fields to the data table.
**签名** **Signature**
* `setFields(fields: FieldOptions[], resetFields = true): Field[]` * `setFields(fields: FieldOptions[], resetFields = true): Field[]`
**参数** **Parameter**
| 参数名 | 类型 | 默认值 | 描述 | | Name | Type | Default | Description |
| --- | --- | --- | --- | | --- | --- | --- | --- |
| `fields` | `FieldOptions[]` | - | 字段配置,详见 [Field](./field) | | `fields` | `FieldOptions[]` | - | Configuration of the fields, refer to [Field](./field) for details |
| `resetFields` | `boolean` | `true` | 是否重置已存在的字段 | | `resetFields` | `boolean` | `true` | Whether to reset existing fields |
**示例** **Example**
```ts ```ts
const posts = db.collection({ name: 'posts' }); const posts = db.collection({ name: 'posts' });
@ -192,19 +191,19 @@ posts.setFields([
### `removeField()` ### `removeField()`
移除数据表已定义对应名称的字段对象。 Remove a field object whose corresponding name has been defined in the data table.
**签名** **Signature**
* `removeField(name: string): void | Field` * `removeField(name: string): void | Field`
**参数** **Parameter**
| 参数名 | 类型 | 默认值 | 描述 | | Name | Type | Default | Description |
| --- | --- | --- | --- | | --- | --- | --- | --- |
| `name` | `string` | - | 字段名称 | | `name` | `string` | - | Name of the field |
**示例** **Example**
```ts ```ts
const posts = db.collection({ const posts = db.collection({
@ -222,13 +221,13 @@ posts.removeField('title');
### `resetFields()` ### `resetFields()`
重置(清空)数据表的字段。 Reset (Empty) fields of the data table.
**签名** **Signature**
* `resetFields(): void` * `resetFields(): void`
**示例** **Example**
```ts ```ts
const posts = db.collection({ const posts = db.collection({
@ -246,19 +245,19 @@ posts.resetFields();
### `hasField()` ### `hasField()`
判断数据表是否已定义对应名称的字段对象。 Check if the data table has defined a field object with the corresponding name.
**签名** **Signature**
* `hasField(name: string): boolean` * `hasField(name: string): boolean`
**参数** **Parameter**
| 参数名 | 类型 | 默认值 | 描述 | | Name | Type | Default | Description |
| --- | --- | --- | --- | | --- | --- | --- | --- |
| `name` | `string` | - | 字段名称 | | `name` | `string` | - | Name of the field |
**示例** **Example**
```ts ```ts
const posts = db.collection({ const posts = db.collection({
@ -276,19 +275,19 @@ posts.hasField('title'); // true
### `findField()` ### `findField()`
查找数据表中符合条件的字段对象。 Find field objects in the data table that match the conditions.
**签名** **Signature**
* `findField(predicate: (field: Field) => boolean): Field | undefined` * `findField(predicate: (field: Field) => boolean): Field | undefined`
**参数** **Parameter**
| 参数名 | 类型 | 默认值 | 描述 | | Name | Type | Default | Description |
| --- | --- | --- | --- | | --- | --- | --- | --- |
| `predicate` | `(field: Field) => boolean` | - | 查找条件 | | `predicate` | `(field: Field) => boolean` | - | The condition |
**示例** **Example**
```ts ```ts
const posts = db.collection({ const posts = db.collection({
@ -306,19 +305,19 @@ posts.findField(field => field.name === 'title');
### `forEachField()` ### `forEachField()`
遍历数据表中的字段对象。 Iterate over field objects in the data table.
**签名** **Signature**
* `forEachField(callback: (field: Field) => void): void` * `forEachField(callback: (field: Field) => void): void`
**参数** **Parameter**
| 参数名 | 类型 | 默认值 | 描述 | | Name | Type | Default | Description |
| --- | --- | --- | --- | | --- | --- | --- | --- |
| `callback` | `(field: Field) => void` | - | 回调函数 | | `callback` | `(field: Field) => void` | - | Callback function |
**示例** **Example**
```ts ```ts
const posts = db.collection({ const posts = db.collection({
@ -334,24 +333,24 @@ const posts = db.collection({
posts.forEachField(field => console.log(field.name)); posts.forEachField(field => console.log(field.name));
``` ```
## 索引配置方法 ## Index Configuration Method
### `addIndex()` ### `addIndex()`
添加数据表索引。 Add data table index.
**签名** **Signature**
* `addIndex(index: string | string[] | { fields: string[], unique?: boolean,[key: string]: any })` * `addIndex(index: string | string[] | { fields: string[], unique?: boolean,[key: string]: any })`
**参数** **Parameter**
| 参数名 | 类型 | 默认值 | 描述 | | Name | Type | Default | Description |
| --- | --- | --- | --- | | --- | --- | --- | --- |
| `index` | `string \| string[]` | - | 需要配置索引的字段名 | | `index` | `string \| string[]` | - | Names of fields to be indexed |
| `index` | `{ fields: string[], unique?: boolean, [key: string]: any }` | - | 完整配置 | | `index` | `{ fields: string[], unique?: boolean, [key: string]: any }` | - | Full configuration |
**示例** **Example**
```ts ```ts
const posts = db.collection({ const posts = db.collection({
@ -372,19 +371,19 @@ posts.addIndex({
### `removeIndex()` ### `removeIndex()`
移除数据表索引。 Remove data table index.
**签名** **Signature**
* `removeIndex(fields: string[])` * `removeIndex(fields: string[])`
**参数** **Parameter**
| 参数名 | 类型 | 默认值 | 描述 | | Name | Type | Default | Description |
| --- | --- | --- | --- | | --- | --- | --- | --- |
| `fields` | `string[]` | - | 需要移除索引的字段名组合 | | `fields` | `string[]` | - | Names of fields to remove indexes |
**示例** **Example**
```ts ```ts
const posts = db.collection({ const posts = db.collection({
@ -406,17 +405,17 @@ const posts = db.collection({
posts.removeIndex(['title']); posts.removeIndex(['title']);
``` ```
## 表配置方法 ## Table Configuration Method
### `remove()` ### `remove()`
删除数据表。 Remove data table.
**签名** **Signature**
* `remove(): void` * `remove(): void`
**示例** **Example**
```ts ```ts
const posts = db.collection({ const posts = db.collection({
@ -432,17 +431,17 @@ const posts = db.collection({
posts.remove(); posts.remove();
``` ```
## 数据库操作方法 ## Database Operation Method
### `sync()` ### `sync()`
同步数据表定义到数据库。除了 Sequelize 中默认的 `Model.sync` 的逻辑,还会一并处理关系字段对应的数据表。 Synchronize the definitions in data table to the database. In addition to the default `Model.sync` logic in Sequelize, the data tables corresponding to the relational fields will also be handled together.
**签名** **Signature**
* `sync(): Promise<void>` * `sync(): Promise<void>`
**示例** **Example**
```ts ```ts
const posts = db.collection({ const posts = db.collection({
@ -460,19 +459,19 @@ await posts.sync();
### `existsInDb()` ### `existsInDb()`
判断数据表是否存在于数据库中。 Check whether the data table exists in the database.
**签名** **Signature**
* `existsInDb(options?: Transactionable): Promise<boolean>` * `existsInDb(options?: Transactionable): Promise<boolean>`
**参数** **Parameter**
| 参数名 | 类型 | 默认值 | 描述 | | Name | Type | Default | Description |
| --- | --- | --- | --- | | --- | --- | --- | --- |
| `options?.transaction` | `Transaction` | - | 事务实例 | | `options?.transaction` | `Transaction` | - | Transaction instance |
**示例** **Example**
```ts ```ts
const posts = db.collection({ const posts = db.collection({
@ -492,20 +491,20 @@ console.log(existed); // false
### `removeFromDb()` ### `removeFromDb()`
**签名** **Signature**
* `removeFromDb(): Promise<void>` * `removeFromDb(): Promise<void>`
**示例** **Example**
```ts ```ts
const books = db.collection({ const books = db.collection({
name: 'books' name: 'books'
}); });
// 同步书籍表到数据库 // Synchronize the table books to the database
await db.sync(); await db.sync();
// 删除数据库中的书籍表 // Remove the table books from the database
await books.removeFromDb(); await books.removeFromDb();
``` ```