我正在为新项目使用Vapor 3
和FluentMySQL
,并希望通过迁移来更改字段的最大长度(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))
}
}
它没有用;什么都没发生。
如何通过Vapor
,FluentMySQL
和迁移来更改表的结构?
您可以使用这样的原始查询执行任何操作
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))
}
}
不是使用addProperties(to:)
将所有字段添加到数据库,而是可以使用field(for:type:_:)
手动添加字段。