在 vapor fluent 中查找所有具有空的多对多关系的项目

Find all items with empty many to many relationship in vapor fluent

以 vapor 文档中的示例为例:

// 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]
}

如何使用fluent查询所有没有标签的行星?

Planet.query(on: req.db).filter(?).all()

编辑:解决方案,但 async/await

let pivots = try await PlanetTag.query(on: req.db).unique().all()
let planetsWithTags = pivots.map { [=12=].$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 { [=10=].tags.isEmpty }
    // continue processing
}

这有点浪费,因为您正在获取(可能)很多您不需要的记录。更好的方法是获取确实有标签的行星,然后排除这些行星:

PlanetTag.query(on:req.db).unique().all(\.$planet).flatMap { planetTags in
    return Planet.query(on:req.db).filter(\.$id !~ planetTags.map { [=11=].$planet.$id }).all().flatMap { planetsWithoutTags in 
        // continue processing
    }
}