[英]Add Foreign Key Constraint Swift Vapor Fluent with PostgreSQL
[英]Vapor fluent doesn't throw upon violating foreign key constraint
當我使用 create 向數據庫添加模型時,當違反其中一個外鍵時,Vapor fluent 不會引發異常。 它也沒有插入,創建函數只是正常返回。
這是 Vapor Fluent 的標准行為嗎?
我在 PostgreSQL 中使用 Vapor 3。
這是我添加外鍵約束的遷移:
struct AddAddressForeignKeys: Migration {
typealias Database = PostgreSQLDatabase
static func prepare(on conn: PostgreSQLConnection) -> Future<Void> {
return PostgreSQLDatabase.update(Address.self, on: conn) { builder in
builder.reference(from: \.regionId, to: \CodeRegion.id)
builder.reference(from: \.countryId, to: \CodeCountry.id)
}
}
static func revert(on conn: PostgreSQLConnection) -> Future<Void> {
return PostgreSQLDatabase.update(Address.self, on: conn) { builder in
builder.deleteReference(from: \.regionId, to: \CodeRegion.id)
builder.deleteReference(from: \.countryId, to: \CodeCountry.id)
}
}
}
更新:我已經添加了 Jacob Relkin 的回答中提到的 enableReferences ,但仍然沒有拋出異常。 H
// Configure database
let config = PostgreSQLDatabaseConfig(hostname: "localhost", port: 5432, username: "postgres", database: "test", password: nil, transport: .cleartext)
let postgres = PostgreSQLDatabase(config: config)
// Register the configured database to the database config.
var databases = DatabasesConfig()
databases.add(database: postgres, as: .psql)
databases.enableReferences(on: .psql)
services.register(databases)
為了強制執行外鍵違規,您必須在設置DatabasesConfig
時調用enableReferences(on:)
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.