繁体   English   中英

在 Vapor Fluent-MySQL 中通过迁移更改 VARCHAR 字段

[英]Change a VARCHAR field via migration in Vapor Fluent-MySQL

我正在将Vapor 3FluentMySQL用于我的新项目,并希望通过迁移更改字段的最大长度 ( varchar(N) )。 我怎样才能做到这一点?

我的项目中有一个名为Word的模型,其中一个字段是sourceIdentifier ,它是String ,最大长度为 12。模型是这样的:

final class Word: MySQLModel {
    ...other properties

    var sourceIdentifier: String

    ...other properties
}

一开始以为5个字段就够了,用这段代码为这个模型创建了Table

static func prepare(on conn: MySQLConnection) -> Future<Void> {
    return MySQLDatabase.create(Word.self, on: conn) { builder in
        ...other fields...

        builder.field(for: \.sourceIdentifier, type: .varchar(5, characterSet: nil, collate: nil))

        ...other fields...
    }
}

如上所示,使用字段sourceIdentifier创建的表及其类型为.varchar(5, characterSet: nil, collate: nil)

现在我想通过迁移增加字段的最大长度。

我也试过MySQLDatabase.update这样的:

static func prepare(on conn: MySQLConnection) -> Future<Void> {
    return MySQLDatabase.update(Word.self, on: conn) { builder in
        builder.field(for: \.sourceIdentifier, type: .varchar(12, characterSet: nil, collate: nil))
    }
}

它没有用; 什么都没有发生。

如何通过VaporFluentMySQL和迁移更改表的结构?

你可以用这样的原始查询做任何事情

static func prepare(on conn: MySQLConnection) -> Future<Void> {
    return conn.raw("ALTER TABLE emp MODIFY COLUMN name VARCHAR(100);").run()
}

你可以试试这个。

static func prepare(on conn: MySQLConnection) -> Future<Void> {
  return Database.create(self, on: connection) { builder in
    builder.field(for: \.id, type: .bigint(20), .primaryKey)
    builder.field(for: \.fieldA, type: .varchar(12))
    builder.field(for: \.fieldB, type: .bigint(20))
  }
}

您可以使用field(for:type:_:)手动添加字段,而不是使用addProperties(to:)将所有字段添加到数据库中。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM