表结构和数据库迁移

未匹配的标注

架构和迁移

迁移用于构建和修改数据库表。这是通过使用迁移文件和Schema类来完成的。迁移文件实际上只是Schema类的包装器,也是 Masonite 管理哪些迁移已运行和哪些未运行的一种方式。

创建迁移

使用迁移命令可以轻松创建迁移。要创建一个,只需运行:

$ masonite-orm migration migration_for_users_table

这将为您创建一个迁移文件并将其放在databases/migrations目录中。

如果您想创建一个入门迁移,即包含您计划执行的一些样板的迁移,您可以使用--table--create标签:

$ masonite-orm migration migration_for_users_table --create users

这将为您在创建新表时设置迁移操作,并在创建新表时使用一些样板

$ masonite-orm migration migration_for_users_table --table users

这将为您在修改现有表时为样板设置迁移。

构建迁移

要开始构建您的迁移,只需修改up方法并开始将以下任何可用方法添加到您的迁移中。

对于新表,一个简单的示例如下所示:

class MigrationForUsersTable(Migration):
    def up(self):
        """
        Run the migrations.
        """
        with self.schema.create("users") as table:
            table.increments('id')
            table.string('username')
            table.string('email').unique()
            table.string('password')
            table.boolean('is_admin')
            table.integer('age')

            table.timestamps()

    def down(self):
        """
        Revert the migrations.
        """
        self.schema.drop("users")

可用方法

命令 说明
table.string() 表的 varchar 版本。可以可选传入长度table.string('name', length=181)
table.char() CHAR 等效列。
table.text() TEXT 等效列。
table.longtext() LONGTEXT 等效列。
table.integer() 数据库的 INT 版本。也可以指定长度table.integer('age', length=5)
table.unsigned_integer() UNSIGNED INT 等效列。
table.unsigned() unsigned_integer的别名
table.tiny_integer() TINY INT 等效列。
table.small_integer() SMALL INT 等效列。
table.medium_integer() MEDIUM INT 等效列。
table.big_integer() BIG INT 等效列。
table.increments() 表的自动递增版本。一个无符号、不可为空的自动递增整数。
table.tiny_increments() TINY 自动递增等效列。
table.big_increments() 一个无符号、不可为空的自动递增大整数。如果您希望表中的行非常大,请使用它
table.binary() BINARY 等效列。有时是不受支持的数据库上的文本字段。
table.boolean() BOOLEAN 等效列。
table.json() JSON 等效列。
table.jsonb() LONGBLOB 等效列。 Postgres 的 JSONB 等效列。
table.date() DATE 等效列。
table.year() YEAR 等效列。
table.datetime() DATETIME 等效列。
table.timestamp() TIMESTAMP 等效列。
table.time() TIME 等效列。
table.timestamps() 在具有timestamp列的表上创建created_atupdated_at列,默认为当前时间。
table.decimal() DECIMAL 等效列。还可以指定长度和小数位。table.decimal('salary', 17, 6)
table.double() DOUBLE 等效列。也可以指定浮点长度table.double('salary', 17,6)
table.float() FLOAT 等效列。
table.enum() ENUM 等效列。您还可以将可用选项指定为列表。table.enum('flavor', ['chocolate', 'vanilla']).有时默认为对不受支持的数据库有约束的 TEXT 字段。
table.geometry() GEOMETRY 等效列。
table.point() POINT 等效列。
table.uuid() 用于存储 UUIDtable.uuid('id')的 CHAR 列。默认长度为 36。
table.soft_deletes() 一个名为deleted_at的可为空的 DATETIME 列。这由 SoftDeletes 范围使用。
table.table_comment("用户表") 向表格添加注释。

更改和回滚迁移

除了构建迁移之外,您还应该构建down方法,该方法应该反转up方法中所做的任何事情。如果在 up 方法中创建表,则应在 down 方法中删除表。

命令 说明
table.drop_table() DROP TABLE 等效语句。
table.drop_table_if_exists() DROP TABLE IF EXISTS 等效语句。
table.drop_column() DROP COLUMN 等效语句。可以采用一个或多个列名。drop_column('column1', 'column2')
table.drop_index() 删除约束。必须传入约束的名称。drop_index('email_index')
table.drop_unique() 删除唯一性约束。必须传入约束的名称。table.drop_unique('users_email_unique')
table.drop_foreign() 删除外键。必须指定索引名称。table.drop_foreign('users_article_id_foreign')
table.rename() 将列重命名为新列。必须取旧列名、新列和数据类型。table.rename("user_id", "profile_id", "unsigned_integer")
table.drop_primary() 删除主键约束。必须传入约束名称table.drop_primary('users_id_primary')

获取迁移状态

您可以随时获取已运行或需要运行的迁移:

$ masonite-orm migrate:status

查看迁移 SQL 转储

如果您只想查看将运行的 SQL 而不是运行实际迁移,可以指定-s标志 (--show\ 的缩写)。这适用于 migrate 和 migrate:rollback 命令。

python craft migrate -s

恢复迁移

恢复数据库只是回滚所有迁移,然后再次迁移。这会“刷新”您的数据库。

您可以通过运行以下命令进行恢复:

$ masonite-orm migrate:refresh

您还可以在恢复迁移后为您的数据库填充。这会将您的数据库重建到某种期望状态。

您可以通过以下方式运行位于Database Seeder类中的所有填充:

$ masonite-orm migrate:refresh --seed

或者简单地运行一个特定的填充:

$ masonite-orm migrate:refresh --seed CustomTable

CustomTable 是没有“Seeder”后缀的填充名称。在内部,我们将运行所需的 CustomTableSeeder。

修饰符

除了可以使用的可用列之外,您还可以指定一些将改变列的行为的修饰符:

命令 说明
.nu​​llable() 允许将 NULL 值插入到列中。
.唯一() 强制列中的所有值都是唯一的。
.after(other_column) 在表中的另一列之后添加该列。可以像table.string('is_admin').after('email')一样使用。
.无符号() 使列无符号。与table.integer('age').unsigned()列一起使用。
.use_current() 使列使用CURRENT_TIMESTAMP修饰符。
.default(值) 指定列的默认值。可以像 table.boolean("is_admin").default(False) 一样使用
.primary() 指定该列应用于主键约束。像table.string('role_id').primary() 一样使用
.comment() 向列添加注释。像table.string('name').comment("A users name") 一样使用

索引

除了列之外,您还可以创建索引。以下是您可以创建的可用索引:

命令 说明
table.primary(column) 创建主表约束。可以传递多个列来创建像table.primary(['id', 'email'])这样的复合键。还支持name参数来指定索引的名称。
table.unique(column) 创建唯一索引。也可以传递多列table.unique(['email', 'phone_number'])。还支持name参数来指定索引的名称。
table.index(column) 在列上创建索引。table.index('email')。还支持name参数来指定索引的名称。
table.fulltext(column) 在一个或多个列上创建全文索引。table.fulltext('email')。请注意,这仅适用于 MySQL 数据库,在其他数据库上将被忽略。还支持name参数来指定索引的名称。

默认主键通常设置为自动递增整数,但您可以改用 UUID

外键

如果你想创建一个外键,你也可以这样做:

table.foreign('local_column').references('other_column').on('other_table')

并且可以选择指定on_deleteon_update方法:

table.foreign('local_column').references('other_column').on('other_table').on_update('set null')

您可以使用以下选项:

Command Description
.on_update('set null') 在约束上设置 ON UPDATE SET NULL 属性。
.on_update('cascade') 设置约束的 ON UPDATE CASCADE 属性。
.on_delete('set null') 在约束上设置 ON DELETE SET NULL 属性。
.on_delete('cascade') 设置约束的 ON DELETE CASCADE 属性。

on_updateon_delete的可用选项有:

  • cascade
  • set null
  • restrict
  • no action
  • default

您还可以传递name参数来更改约束的名称:

table.foreign('local_column', name="foreign_constraint").references('other_column').on('other_table')

您也可以使用速记方法:

table.add_foreign('local_column.other_column.other_table', name="foreign_constraint")

更改列

如果您想更改列,您只需指定新列,然后在其上指定.change()方法。

以下是将电子邮件字段更改为可空字段的示例:

class MigrationForUsersTable(Migration):
    def up(self):
        """
        Run the migrations.
        """
        with self.schema.table("users") as table:
            table.string('email').nullable().change()

        with self.schema.table("users") as table:
            table.string('email').unique()

    def down(self):
        """
        Revert the migrations.
        """
        pass

截断

您可以截断表格:

schema.truncate("users")

您还可以暂时禁用外键检查并截断表:

schema.truncate("users", foreign_keys=False)

删除表

您可以删除一个表:

schema.drop_table("users")

如果表存在则删除表

如果表存在,您可以删除它:

schema.drop_table_if_exists("users")

本文章首发在 LearnKu.com 网站上。

本译文仅用于学习和交流目的,转载请务必注明文章译者、出处、和本文链接
我们的翻译工作遵照 CC 协议,如果我们的工作有侵犯到您的权益,请及时联系我们。

原文地址:https://learnku.com/docs/masonite/4.0/or...

译文地址:https://learnku.com/docs/masonite/4.0/or...

上一篇 下一篇
贡献者:3
讨论数量: 0
发起讨论 只看当前版本


暂无话题~