[英]Crash on Join with Fluent in Vapor
我有兩個模型,他們有一對多關系。 這是我的課程。
預訂
final class Booking: PostgreSQLModel {
/// The unique identifier for this `Todo`.
var id: Int?
/// A title describing what this `Todo` entails.
var user_id: User.ID
var product_id: Product.ID
var count: Int
/// Creates a new `Todo`.
init(id: Int? = nil, user_id: User.ID, product_id: Product.ID, count: Int) {
self.id = id
self.user_id = user_id
self.product_id = product_id
self.count = count
}
}
extension Booking {
var user: Parent<Booking, User> {
return parent(\.user_id)
}
var product: Parent<Booking, Product> {
return parent(\.product_id)
}
}
產品
final class Product: PostgreSQLModel {
/// The unique identifier for this `Todo`.
var id: Int?
/// A title describing what this `Todo` entails.
var name: String
var image_url: String
var description: String
var price: Int?
/// Creates a new `Todo`.
init(id: Int? = nil, name: String, image_url: String, description: String, price: Int) {
self.id = id
self.name = name
self.image_url = image_url
self.description = description
self.price = price
}
}
extension Product {
var bookings: Children<Product, Booking> {
return children(\.product_id)
}
}
現在我想獲取用戶的所有預訂,並且每次預訂我也想獲取產品信息。 所以為此,我試圖加入Booking
和Product
表,但這引發了一個例外。
致命錯誤:'試試!' 表達式意外地引發了錯誤:⚠️CoreError:
Parent<Booking, Product>
不符合ReflectionDecodable
。 - id:CoreError.ReflectionDecodable:file /BuildRoot/Library/Caches/com.apple.xbs/Sources/swiftlang_Fall2018/swiftlang_Fall2018-1000.11.42/src/swift/stdlib/public/core/ErrorType.swift,第184行程序結束於退出代碼:9
這是我加入的代碼。
let booking = Booking.query(on: req).join(\Product.bookings, to:\Booking.product).filter(\.user_id == userID).decode(BookingM.self).all()
首先,使用您擁有的查詢,您不需要加入Product
表,因為您從不查詢或解碼它。
您的join
聲明:
.join(\Product.bookings, to:\Booking.product)
是不正確的。 您應該加入Product.bookings
屬性,而不是加入Product.id
屬性,因為產品的ID是Booking.product
屬性所包含的。
所以你的Fluent查詢應該是這樣的:
let booking = Booking.query(on: req).join(\Booking.product, to:\Product.id).filter(\.user_id == userID).all()
我刪除了.decoding
調用,因為查詢已經將查詢結果解碼為Booking
。
要使用您的bookings
屬性,您的查詢將如下所示:
let booking = product.bookings.query(on: req).filter(\Booking.user_id == userID).all()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.