简体   繁体   English

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

[英]Find all items with empty many to many relationship in vapor fluent

Given the example from the vapor docs:给出蒸气文档中的示例:

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

How can I query with fluent all pl.nets which do not have a tag?我怎样才能流畅地查询所有没有标签的 pl.net?

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

EDIT: Solution but with async/await编辑:解决方案,但使用异步/等待

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)

I haven't checked this out but, intuitively, this should work if you want to make use of the Sibling relationship:我还没有检查过这个,但直觉上,如果你想利用Sibling关系,这应该可行:

Planet.query(on:req.db).with(\.$tags).all().map { allPlanets in
    let planetWithoutTags = allPlanets.filter { $0.tags.isEmpty }
    // continue processing
}

This is a bit wasteful, since you are fetching (potentially) lots of records that you don't want.这有点浪费,因为您正在获取(可能)很多您不需要的记录。 A better approach is to get the pl.nets that do have tags and then exclude those:更好的方法是获取具有标签的 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM