架构构建器
架构构建器允许你create、alter、drop 和执行其他 SQL DDL 操作。
你可以使用迁移文件中的 this.schema
属性访问架构构建器实例。
import BaseSchema from '@ioc:Adonis/Lucid/Schema'
class UserSchema extends BaseSchema {
public up() {
console.log(this.schema)
}
}
方法/属性
以下是模式构建器类上可用的方法/属性列表。
createTable
创建一个新的数据库表。 该方法接受表名和接收 table builder 实例以创建表列的回调。
class UserSchema extends BaseSchema {
public up() {
this.schema.createTable('users', (table) => {
table.increments()
table.string('name')
table.timestamp('created_at', { useTz: true })
table.timestamp('updated_at', { useTz: true })
})
}
}
createSchema
创建 PostgreSQL 架构。 它接受模式名称。
class FoundationSchema extends BaseSchema {
public up() {
this.schema.createSchema('public')
}
}
表/更改表
选择一个 SQL 表以更改其列。 该方法接受表名和接收 table builder 实例以修改表列的回调。
class UserSchema extends BaseSchema {
public up() {
this.schema.alterTable('user', (table) => {
/**
* 删除 name 列
*/
table.dropColumn('name')
/**
* 添加 first_name 和 last_name 列
*/
table.string('first_name')
table.string('last_name')
})
}
}
renameTable
重命名表。 该方法接受现有表名作为第一个参数,新名称作为第二个参数。
class UserSchema extends BaseSchema {
public up() {
this.schema.renameTable('user', 'app_users')
}
}
dropTable
删除现有的 SQL 表。 该方法接受表名作为唯一参数。
class UserSchema extends BaseSchema {
public down() {
this.schema.dropTable('users')
}
}
dropTableIfExists
类似于 dropTable
方法,但如果表存在则有条件地删除它。
class UserSchema extends BaseSchema {
public down() {
this.schema.dropTableIfExists('users')
}
}
dropSchema
删除现有的 PostgreSQL 模式。 该方法接受模式名称作为唯一参数。
class FoundationSchema extends BaseSchema {
public down() {
this.schema.dropSchema('public')
}
}
dropSchemaIfExists
类似于 dropSchema
方法,但有条件地删除模式(如果存在)。
class FoundationSchema extends BaseSchema {
public down() {
this.schema.dropSchemaIfExists('public')
}
}
raw
从原始字符串运行 SQL 查询。 与 原始查询构建器 不同,schema.raw
方法不单独接受绑定。
class UserSchema extends BaseSchema {
public up() {
this.schema
.raw("SET sql_mode='TRADITIONAL'")
.table('users', (table) => {
table.dropColumn('name')
table.string('first_name')
table.string('last_name')
})
}
}
withSchema
指定运行 SQL DDL 语句时要选择的架构。 该方法接受模式名称作为唯一参数。
class UserSchema extends BaseSchema {
public up() {
this.schema
.withSchema('public')
.createTable('users', (table) => {
table.increments()
table.string('name')
table.timestamp('created_at', { useTz: true })
table.timestamp('updated_at', { useTz: true })
})
}
}
本译文仅用于学习和交流目的,转载请务必注明文章译者、出处、和本文链接
我们的翻译工作遵照 CC 协议,如果我们的工作有侵犯到您的权益,请及时联系我们。