[英]In Fluent / Vapor 4, how do I filter a list based on a foreign key?
所以我有模型名稱Organization
、 User
和App
。 應用程序和用戶都屬於組織。
final class Organization: Model, Content {
static let schema = "organizations"
@ID(key: .id)
var id: UUID?
@Field(key: "name")
var name: String
@Children(for: \.$organization)
var users: [User]
}
final class App: Model, Content {
static let schema = "apps"
@ID(key: .id)
var id: UUID?
@Field(key: "name")
var name: String
@Parent(key: "organization_id")
var organization: Organization
}
final class User: Model, Content {
static let schema = "users"
@ID(key: .id)
var id: UUID?
@Field(key: "email")
var email: String
@Field(key: "password_hash")
var passwordHash: String
@Parent(key: "organization_id")
var organization: Organization
}
現在,基本上我想做的是,給定一個用戶,我想獲取屬於該用戶組織的所有應用程序。
我可以從我的身份驗證系統中獲取用戶,但我所擁有的只是這個查詢:
let user = try req.auth.require(User.self)
return App.query(on: req.db).filter(\.$organization.id == user.$organization.id).all()
這將失敗並顯示錯誤消息Operator function '==' requires that 'UUID' conform to 'QueryableProperty'
。
我應該怎么做?
您需要提供要過濾的屬性包裝器的預計值的關鍵路徑,而不是值本身。 因此,正如您發現的那樣:
.filter(\.$organization.$id == user.$organization.id)
您必須使用屬性包裝器的投影值而不是僅使用屬性本身的原因是因為屬性包裝器包含執行查詢所需的信息(如列名),而這些信息僅適用於屬性
來自 Vapor discord 的用戶jimmy#2207
為我提供了這個答案:
let user = try req.auth.require(User.self)
// Only show user's orgs' apps, thanks to @jhoughjr
return App.query(on: req.db)
.filter(\.$organization.$id == user.$organization.id)
.all()
我不完全知道它為什么起作用,但這是反斜杠和美元符號的正確組合。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.