3

这让我很困惑:

我有一个模型,我想在其中使用枚举。我首先声明枚举:

enum MenuChoices: String, Codable {
    case reachableAt
    case attentionTo
    case reasonVisit
    case reasonProblem
}

然后它在我的班级领域:

@Enum(key: "menu_choices")
var menuChoices: MenuChoices

然后我使用迁移在数据库中创建它:

struct CreateUserMenu: Migration {    
func prepare(on database: Database) -> EventLoopFuture<Void> {
    return database.enum("menu_choices")
        .case("reachable_at")
        .case("attention_to")
        .case("reason_visit")
        .case("reason_problem")
        .create()
        .flatMap { menu_choices in
            return database.schema("user_menus")
                .id()
                .field("created_at", .datetime, .required)
                .field("updated_at",.datetime, .required)
                .field("deleted_at",.datetime)
                .field("menu_choices", menu_choices)
                .field("be_nl", .string)
                .field("be_fr", .string)
                .field("en_us", .string)
                .create()
        }
    }
}

到目前为止,一切都很好。此迁移有效,并且数据库看起来没问题。但是当我想在另一个迁移中添加一些数据来为数据库做种时,我得到一个错误:

let test = UserMenu( menuChoices: MenuChoices.reachableAt, beNl: "nl", beFr: "fra", enUs: "eng")
let _ = test.save(on: database)

+ App.addUserMenus on default
Would you like to continue?
y/n> y
[ ERROR ] previousError(MySQL error: Server error: Data truncated for column 'menu_choices' at row 1)
Fatal error: Error raised at top level: previousError(MySQL error: Server error: Data truncated for column 'menu_choices' at row 1): file /AppleInternal/BuildRoot/Library/Caches/com.apple.xbs/Sources/swiftlang/swiftlang-1103.8.25.8/swift/stdlib/public/core/ErrorType.swift, line 200
    USSS-Voyager-II:24yours data$ 

不幸的是,这个错误并不能真正帮助查明问题的根源

4

1 回答 1

3

问题是枚举的 swift 定义和 Fluent 枚举之间没有映射。为您的 swift 枚举定义添加一个与 Fluent 的字符串文字值匹配的字符串文字值将解决问题。

enum MenuChoices: String, Codable {
    case reachableAt = "reachable_at"
    case attentionTo = "attention_to"
    case reasonVisit = "reason_visit"
    case reasonProblem = "reason_problem"
}
于 2020-12-03T22:07:01.273 回答