根据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()

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)

推荐答案

我还没有查出来,但直觉上,如果你想利用Sibling人的关系,这应该是可行的:

Planet.query(on:req.db).with(\.$tags).all().map { allPlanets in
    let planetWithoutTags = allPlanets.filter { $0.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 { $0.$planet.$id }).all().flatMap { planetsWithoutTags in 
        // continue processing
    }
}

Sql相关问答推荐

Postgresql -如何计算刷卡和刷卡时间

对于表A中的每一行,更新表B中与金额有关的行

我如何计算字母a出现的字符串的次数?

在SQL中创建一个计数器,根据BigQuery/SQL中的条件递归地添加行值

如何在联接条件不匹配时按日期获取上一条记录

Select 非重复值并按条件排除行

Oracle 23c ROUND,数据类型为DATE

Postgres SQL查询从字符串中获取邮箱地址

VS代码无法识别SQL代码中带括号的字符串

向表中添加新列取决于表的日期列(unpivot)

获取分布在同一行的列中的出现次数

根据时间值提取记录

在 R 值的 SQL 块中显示值

SQL for Smarties 类型问题:从表中 Select 记录,并对某些值进行分组

PostgreSQL如何将Unix纪元时间戳转换为日期时间并进行拼接

如何从 2 个 SQLite 表构建嵌套对象?

PlSql 陷入死循环

ACCESS SQL - 有没有办法使用通配符仅 Select 字段的特定部分?

pyspark 将列转换为行

如何列出 Oracle 数据库中的所有函数并按修改日期排序