表格构建器
表格生成器允许你在选定的数据库表格上创建,删除,或重命名列。
你可以通过调用以下架构构建器方法之一来获得对表格构建器实例的访问。
class UserSchema extends BaseSchema {
public up() {
this.schema.createTable('users', (table) => {
console.log(table) // 👈 Table builder
})
this.schema.table('users', (table) => {
console.log(table) // 👈 Table builder
})
}
}
方法 / 属性#
以下是表格生成器类中可用的方法 / 属性的列表。
dropColumn#
按名称删除一个列。
this.schema.table('users', (table) => {
table.dropColumn('name')
})
dropColumns#
通过提供多个参数,删除多个列。
this.schema.table('users', (table) => {
table.dropColumns('first_name', 'last_name')
})
renameColumn#
重命名一个列。该方法接受现有的列名作为第一个参数,新名称作为第二个参数。
this.schema.table('users', (table) => {
table.renameColumn('name', 'full_name')
})
increments#
添加一个自动递增的列。除非明确禁止,该列也被标记为主键。
- 在 PostgreSQL 中,该列具有
serial
数据类型。 - 在 Amazon Redshift 中,它是一个
integer indentity (1,1)
。
this.schema.createTable('users', (table) => {
table.increments('id')
})
定义一个递增列,但不把它标记为主键。
this.schema.createTable('users', (table) => {
table.increments('other_id', { primaryKey: false })
})
integer#
添加一个 integer 列。
this.schema.createTable('users', (table) => {
table.integer('visits')
})
bigInteger#
在 MYSQL 和 PostgreSQL 中添加一个 bigint
列。对于所有其他数据库驱动,默认为一个普通的整数。
BigInt 列的值在查询结果中以字符串形式返回。
this.schema.createTable('users', (table) => {
table.bigInteger('visits')
})
text#
在数据库中添加一个 text 列。你可以选择将文本数据类型定义为 mediumtext
或 longtext
。如果底层驱动不是 MySQL,数据类型会被忽略。
this.schema.createTable('posts', (table) => {
table.text('content_markdown', 'longtext')
})
string#
添加一个长度可选的 string 列。如果没有指定,长度默认为 255
。
this.schema.createTable('posts', (table) => {
table.string('title')
// 指定长度
table.string('title', 100)
})
float#
添加一个 可选择精度(默认为 8) 和 刻度(默认为 2) 的 float 列。
this.schema.createTable('products', (table) => {
table.float('price')
/**
* 指定精度和刻度
*/
table.float('price', 8, 2)
})
decimal#
添加一个 可选择精度(默认为 8) 和 刻度(默认为 2) 的 decimal 列,。
将 null
指定为精度会创建一个可以存储精度和尺度数的 decimal 列。(只支持 Oracle 、 SQLite 、 Postgres 数据库)
this.schema.createTable('products', (table) => {
table.decimal('price')
/**
* 指定精度和刻度
*/
table.decimal('price', 8, 2)
})
boolean#
添加一个布尔类型的列。许多数据库在 SQL 查询期间返回相同的值,将 true
和 false
表示为 1
和 0
。
this.schema.createTable('posts', (table) => {
table.boolean('is_published')
})
date#
在数据库表中添加一个日期列。
this.schema.createTable('users', (table) => {
table.date('dob')
})
dateTime#
在数据库表中添加一个 DateTime 列。该方法接受列名作为第一个参数,以及选项对象来配置 precision
并使用 timestampz
数据类型。
- 您可以在 PostgreSQL 中启用 / 禁用
timestampz
数据类型。默认情况下启用。 - 您可以为 MySQL 5.6+ 定义列精度。
this.schema.createTable('users', (table) => {
table
.dateTime('some_time', { useTz: true })
.defaultTo(this.now())
// Or define the precision
table
.dateTime('some_time', { precision: 6 })
.defaultTo(this.now(6))
})
time#
为 MySQL 添加一个可选精度的时间列。在 Amazon Redshift 上不支持。
this.schema.createTable('users', (table) => {
table.time('some_time', { precision: 6 })
})
timestamp#
在数据库表中添加一个时间戳列。该方法接受列名作为第一个参数,以及选项对象来配置 precision
并使用 timestampz
数据类型。
- 您可以在 PostgreSQL 中启用 / 禁用
timestampz
数据类型。默认情况下启用。 - 设置
useTz=true
将在 MSSQL 中使用DATETIME2
数据类型。默认情况下禁用。 - 您可以为 MySQL 5.6+ 定义列精度。
this.schema.createTable('users', (table) => {
table.timestamp('created_at')
// Enable timestampz and DATETIME2 for MSSQL
table.timestamp('created_at', { useTz: true })
// Use precision with MySQL
table.timestamp('created_at', { precision: 6 })
})
timestamps#
向数据库表中添加 created_at
和 updated_at
列。
由于 AdonisJS 底层使用 Knex.js,因此您的编辑器自动完成功能将在可用方法列表中列出 timestamps
方法。
但是,我们建议不要使用此方法,而是使用 timestamp
方法,原因如下:
timestamps
方法不可链式调用,意味着您无法添加其他约束条件,例如index
或nullable
到列中。- 您可以创建
timestampz
或Datetime2
类型的列。
this.schema.createTable('users', (table) => {
table.timestamps()
})
默认情况下,timestamps
方法创建一个 DATETIME 列。但是,您可以通过将 true
作为第一个参数传递来将其更改为 TIMESTAMP 列。
this.schema.createTable('users', (table) => {
/**
* Creates timestamp column
*/
table.timestamps(true)
})
this.schema.createTable('users', (table) => {
/**
* Creates timestamp column
* +
* Set the default value to "CURRENT_TIMESTAMP"
*/
table.timestamps(true, true)
})
binary#
向数据库添加二进制列。该方法接受列名称作为第一个参数,并可选地接受长度作为第二个参数(仅适用于 MySQL)。
this.schema.createTable('users', (table) => {
table.binary('binary_column')
})
enum / enu#
向数据库添加枚举列。该方法接受列名称作为第一个参数,枚举选项数组作为第二个参数,并可选地接受选项对象作为第三个参数。
- 在 PostgreSQL 中,您可以通过将
options.useNative
值设置为true
来使用原生枚举类型。还请确保通过options.enumName
提供唯一名称的枚举名称。 - 在 PostgreSQL 中,我们将在列之前创建枚举。如果枚举类型已存在,则必须将
options.existingType
设置为true
。 - 在 Amazon Redshift 中,使用未经检查的 varchar(255)数据类型。
this.schema.createTable('users', (table) => {
table.enu('account_status', ['PENDING', 'ACTIVE', 'SUSPENDED'], {
useNative: true,
enumName: 'user_account_status',
existingType: false,
})
})
你也可以为枚举类型指定 PostgreSQL 模式。
table.enu('account_status', ['PENDING', 'ACTIVE', 'SUSPENDED'], {
useNative: true,
enumName: 'user_account_status',
existingType: false,
schemaName: 'public' // 👈
})
在删除表时,确保也删除枚举。
this.schema.raw('DROP TYPE IF EXISTS "user_account_status"')
this.schema.dropTable('users')
json#
在 PostgreSQL、MySQL 和 SQLite 中添加 JSON 列,使用内置的 JSON 类型,默认情况下,在旧版本或不支持的数据库中使用文本列。
this.schema.createTable('projects', (table) => {
table.json('settings')
})
jsonb#
与 json 方法相同,但使用本机 jsonb 数据类型(如果可能)。
this.schema.createTable('projects', (table) => {
table.jsonb('settings')
})
uuid#
添加 UUID 列。该方法仅接受列名作为参数。
- 在 PostgreSQL 中使用内置的 UUID 类型
- 对于所有其他数据库,使用
char(36)
this.schema.createTable('users', (table) => {
table.uuid('user_id')
})
确保还要为 PostgreSQL 创建 UUID 扩展。你也可以在专门的迁移文件中执行此操作,如下所示:
import BaseSchema from '@ioc:Adonis/Lucid/Schema'
export default class SetupExtensions extends BaseSchema {
public up() {
this.schema.raw('CREATE EXTENSION IF NOT EXISTS "uuid-ossp"')
}
public down() {
this.schema.raw('DROP EXTENSION IF EXISTS "uuid-ossp"')
}
}
comment#
设置表的注释。接受注释值作为唯一参数。
this.schema.createTable('users', (table) => {
table.comment('Manages the app users')
})
engine#
设置数据库表的引擎。该方法接受引擎名称作为唯一参数。
- 该方法仅在
createTable
调用中可用。 - 引擎仅适用于 MySQL ,对其他数据库无效。
this.schema.createTable('users', (table) => {
table.engine('MyISAM')
})
charset#
设置继承的父表。该方法接受父表名称作为唯一参数。
- 该方法仅在
createTable
调用中可用。 inherits
仅适用于 PostgreSQL ,对其他数据库无效。
this.schema.createTable('users', (table) => {
table.charset('utf8')
})
collate#
设置数据库表的排序规则。该方法接受排序规则值作为唯一参数。
- 该方法仅在
createTable
调用中可用。 - 排序规则仅适用于 MySQL ,对其他数据库无效。
this.schema.createTable('users', (table) => {
table.collate('utf8_unicode_ci')
})
inherits#
设置继承的父表。该方法接受父表名称作为唯一参数。
- 该方法仅在
createTable
调用中可用。 inherits
仅适用于 PostgreSQL ,对其他数据库无效。
this.schema.createTable('capitals', (table) => {
table.inherits('cities')
})
specificType#
通过将其类型定义为原始字符串来创建列。该方法允许您创建未涵盖标准表构建器 API 的数据库列。
第一个参数是列名,第二个参数是列类型。
this.schema.createTable('users', (table) => {
table.specificType('mac_address', 'macaddr')
})
index#
在指定的列上为表添加索引。您必须先创建表,然后才能定义索引。
- 该方法接受一个包含列名的数组作为第一个参数。
- 可选的索引名称作为第二个参数
- 第三个参数是可选的索引类型。索引类型仅适用于 PostgreSQL 和 MySQL 数据库。
this.schema.alterTable('users', (table) => {
table.index(['first_name', 'last_name'], 'user_name_index')
})
dropIndex#
从表列中删除现有索引。该方法接受列作为第一个参数,可选的索引名称作为第二个参数。
this.schema.alterTable('users', (table) => {
table.dropIndex(['first_name', 'last_name'], 'user_name_index')
})
unique#
在指定的列上为表添加唯一索引。除非指定了 indexName
,否则将使用默认索引名称使用列名。
this.schema.alterTable('posts', (table) => {
table.unique(['slug', 'tenant_id'])
})
foreign#
为现有列在表中添加外键约束。使用 foreign
方法时,请确保表已经存在。
- 该方法接受一个或多个列名作为第一个参数。
- 您可以将自定义的
foreignKeyName
作为第二个参数。如果未指定,将使用列名生成它。
this.schema.alterTable('posts', (table) => {
table.foreign('user_id').references('users.id')
})
你还可以链式调用 onDelete
和 onUpdate
方法来定义触发器。
table
.foreign('user_id')
.references('users.id')
.onDelete('CASCADE')
dropForeign#
删除预先存在的外键约束。该方法接受一个或多个列作为第一个参数,第二个参数为可选的外键名称。
this.schema.alterTable('posts', (table) => {
table.dropForeign('user_id')
})
dropUnique#
删除预先存在的唯一索引。该方法接受一个或多个列作为第一个参数,第二个参数为可选的索引名称。
this.schema.alterTable('posts', (table) => {
table.dropUnique('email')
})
dropPrimary#
删除预先存在的主键约束。第一个参数为可选的约束名称(默认为 tablename_pkey
)。
this.schema.alterTable('posts', (table) => {
table.dropPrimary()
})
setNullable#
将列设置为可空。
this.schema.alterTable('posts', (table) => {
table.setNullable('full_name')
})
dropNullable#
从列中删除可空约束。
当列已经有空值时,该操作将失败。
this.schema.alterTable('posts', (table) => {
table.dropNullable('full_name')
})
链式调用方法#
以下是您可以在模式构建方法上链式调用的方法列表,作为列的修饰符。
alter#
将列标记为修改 / 修改而不是默认添加。该方法不受 SQLite 或 Amazon Redshift 驱动程序的支持。
alter 语句不是增量的。您必须重新定义要应用于列的约束条件。
this.schema.alterTable('posts', (table) => {
// drops both NOT NULL constraint and the default value (if applied earlier)
table.integer('age').alter()
})
index#
为当前列定义一个索引。该方法接受以下两个可选参数:
- 可选的索引名称作为第一个参数。
- 第二个参数是可选的索引类型。该索引类型仅适用于 PostgreSQL 和 MySQL 数据库。
this.schema.table('posts', (table) => {
table.string('slug').index('posts_slug')
})
primary#
将当前列标记为主键。可选地,您可以将约束名称定义为第一个参数。
在 Amazon Redshift 上,主键中包含的所有列都必须是非空的。
this.schema.table('posts', (table) => {
table.integer('id').primary()
})
如果要定义复合主键,则必须使用 table.primary
方法。
this.schema.table('posts', (table) => {
table.primary(['slug', 'tenant_id'])
})
unique#
将当前列标记为唯一的。在 Amazon Redshift 上,此约束不受强制执行,但查询计划器使用它。
this.schema.table('users', (table) => {
table.string('email').unique()
})
references#
将当前列引用的列定义为外键。
this.schema.table('posts', (table) => {
table.integer('user_id').references('id').inTable('users')
})
你也可以将 tableName.columnName
一起定义,完全删除 inTable
方法。
this.schema.table('posts', (table) => {
table.integer('user_id').references('users.id')
})
inTable#
定义外键引用的列所在的表。
this.schema.table('posts', (table) => {
table.integer('user_id').references('id').inTable('users')
})
onDelete#
定义外键的 onDelete
命令。命令以字符串形式表示。
this.schema.table('posts', (table) => {
table
.integer('user_id')
.references('id')
.inTable('users')
.onDelete('CASCADE')
})
onUpdate#
定义外键的 onUpdate
命令。命令以字符串形式表示。
this.schema.table('posts', (table) => {
table
.integer('user_id')
.references('id')
.inTable('users')
.onUpdate('RESTRICT')
})
defaultTo#
定义插入时要使用的列的默认值。
在 MSSQL 中,可以传递 constraintName 选项以确保使用特定的约束名:
this.schema.table('posts', (table) => {
table.boolean('is_published').defaultTo(false)
// For MSSQL
table
.boolean('is_published')
.defaultTo(false, { constraintName: 'df_table_value' })
})
unsigned#
将当前列标记为无符号数。
this.schema.table('posts', (table) => {
table
.integer('user_id')
.unsigned() // 👈
.references('id')
.inTable('users')
})
notNullable#
将当前列标记为 NOT NULL。
在更改列时,考虑使用 dropNullable 方法。
this.schema.table('users', (table) => {
table.integer('email').notNullable()
})
nullable#
将当前列标记为可空。
在修改列时,考虑使用 setNullable
方法。
this.schema.table('users', (table) => {
table.text('bio').nullable()
})
first#
将要插入的列设置为第一位置,仅在 MySQL 修改表中使用。
this.schema.alterTable('users', (table) => {
table.string('email').first()
})
after#
将要插入的列设置为另一列后面,仅在 MySQL 修改表中使用。
this.schema.alterTable('users', (table) => {
table.string('avatar_url').after('password')
})
comment#
为列设置注释。
this.schema.alterTable('users', (table) => {
table.string('avatar_url').comment('Only relative names are stored')
})
collate#
为列设置校对规则(仅适用于 MySQL)。
this.schema.alterTable('users', (table) => {
table
.string('email')
.unique()
.collate('utf8_unicode_ci')
})
本译文仅用于学习和交流目的,转载请务必注明文章译者、出处、和本文链接
我们的翻译工作遵照 CC 协议,如果我们的工作有侵犯到您的权益,请及时联系我们。