Boryk
Boryk

Reputation: 88

How to filter a nested relationship with Vapor Fluent

I have a relationship that is structured like:

Book {
    id: UUID
    author: Author
}

Author {
    id: UUID
    genre: Genre
}

Genre {
    id: UUID
    name: String
}

I want to be able to query for books that have authors that have a specialize in a specific genre.

I want to do something like:

let query = Book.query(on: db)
    .with(\.$author) { author in
        author.with(\Author.$genre)
    }
    .filter(\Book.$author.$genre.$name, .equal, "Mystery")

But I am getting issues with accessing the genre field from the author.

If I change it to:

.filter(\Book.author.$genre.$name, .equal, "Mystery")

I get an error where it says author wasn't eager loaded.

Upvotes: 1

Views: 39

Answers (1)

Nick
Nick

Reputation: 5200

As far as I know, in Vapor 4 at least, there isn't a way of filtering nested queries as you are hoping.

Assuming your models have @Children from Genre to Author and Author to Books, I would start by filtering on the appropriate Genre and then use nested with to get the authors and then their books. Use map to return an array of 'grand-children' Books. This assumes that your authors only write for one genre, but that is what your example models imply.

Upvotes: 0

Related Questions