From 5f0938a3f5f1a751ff7a411117bfce4efe713526 Mon Sep 17 00:00:00 2001 From: matsuji Date: Sat, 23 Mar 2024 10:37:53 +0900 Subject: [PATCH] Skip DB execution when all ids for @OptionalParent are nil (#583) Co-authored-by: Gwynne Raskind --- Sources/FluentKit/Properties/OptionalParent.swift | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/Sources/FluentKit/Properties/OptionalParent.swift b/Sources/FluentKit/Properties/OptionalParent.swift index af21ce09..aa28d3c8 100644 --- a/Sources/FluentKit/Properties/OptionalParent.swift +++ b/Sources/FluentKit/Properties/OptionalParent.swift @@ -173,6 +173,12 @@ private struct OptionalParentEagerLoader: EagerLoader var sets = Dictionary(grouping: models, by: { $0[keyPath: self.relationKey].id }) let nilParentModels = sets.removeValue(forKey: nil) ?? [] + if sets.isEmpty { + // Fetching "To" objects is unnecessary when no models have an id for "To". + nilParentModels.forEach { $0[keyPath: self.relationKey].value = .some(.none) } + return database.eventLoop.makeSucceededVoidFuture() + } + let builder = To.query(on: database).filter(\._$id ~~ Set(sets.keys.compactMap { $0 })) if (self.withDeleted) { builder.withDeleted()