[英]Find all items with empty many to many relationship in vapor fluent
给出蒸气文档中的示例:
// Example of a pivot model.
final class PlanetTag: Model {
static let schema = "planet+tag"
@ID(key: .id)
var id: UUID?
@Parent(key: "planet_id")
var planet: Planet
@Parent(key: "tag_id")
var tag: Tag
init() { }
init(id: UUID? = nil, planet: Planet, tag: Tag) throws {
self.id = id
self.$planet.id = try planet.requireID()
self.$tag.id = try tag.requireID()
}
}
final class Planet: Model {
// Example of a siblings relation.
@Siblings(through: PlanetTag.self, from: \.$planet, to: \.$tag)
public var tags: [Tag]
}
final class Tag: Model {
// Example of a siblings relation.
@Siblings(through: PlanetTag.self, from: \.$tag, to: \.$planet)
public var planets: [Planet]
}
我怎样才能流畅地查询所有没有标签的 pl.net?
Planet.query(on: req.db).filter(?).all()
编辑:解决方案,但使用异步/等待
let pivots = try await PlanetTag.query(on: req.db).unique().all()
let planetsWithTags = pivots.map { $0.$planet.id }
let planetsWithoutTags = Planet.query(on: req.db).filter(\.$id !~ planetsWithTags)
return try await planetsWithoutTags.paginate(for: req).map(\.detail)
我还没有检查过这个,但直觉上,如果你想利用Sibling
关系,这应该可行:
Planet.query(on:req.db).with(\.$tags).all().map { allPlanets in
let planetWithoutTags = allPlanets.filter { $0.tags.isEmpty }
// continue processing
}
这有点浪费,因为您正在获取(可能)很多您不需要的记录。 更好的方法是获取具有标签的 pl.net,然后排除这些标签:
PlanetTag.query(on:req.db).unique().all(\.$planet).flatMap { planetTags in
return Planet.query(on:req.db).filter(\.$id !~ planetTags.map { $0.$planet.$id }).all().flatMap { planetsWithoutTags in
// continue processing
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.