fluent-kit
fluent-kit copied to clipboard
Soft-deleted Parent relationship don't load even withDeleted
The following query:
Planet.query(on: req.db).with(\.$star).withDeleted().all().map { planets in
for planet in planets {
print(planet.star)
}
}
will crash the process with:
Fatal error: Parent relation not eager loaded, use $ prefix to access: Parent<Planet, Star>(key: star_id)
if a referenced Star
is soft-deleted, despite the withDeleted
call.
Here are some ideas for future discussion:
- Should a
withDeleted
on a top-level query really trickle down to eager loads or do we only want a way to modify an eager load to return deleted objects? I would prefer the latter. - What would really make sense for me would be a way to configure at the relationship definition level if they should always load deleted objects or not:
@Parent(key: "star_id", withDeleted: true)
Related to https://github.com/vapor/fluent-kit/issues/227
@tanner0101 I can't remember if you mentioned if there was a workaround meanwhile?
Can you do:
Planet.query(on: req.db).with(\.$star) { star in
star.withDeleted()
}.withDeleted().all().map { planets in
for planet in planets {
print(planet.star)
}
}
No, that doesn't compile:
error: Value of type 'NestedEagerLoadBuilder<QueryBuilder<Planet>, ParentProperty<Planet, Star>>' has no member 'withDeleted'
Annoying but one option to add the API to
It would be great if withDeleted()
also applied to eager loaded relationships. In the meantime, here's the work-around that worked for me:
Child.query(on: request.db)
.withDeleted()
.all()
.flatMap { children in
request.eventLoop.makeSucceededFuture(children)
.flatMapEach(on: request.eventLoop) { child in
child.$parent
.query(on: request.db)
.withDeleted()
.first()
.map { parent in
child[keyPath: \.$parent].value = parent
}
}
.map {
children
}
}