Skip to content

Nested hierarchy using common table expressions #1486

Answered by groue
seanmrich asked this question in Q&A
Discussion options

You must be logged in to vote

Hello @seanmrich,

I'm afraid you'll have to write your own code in order to fetch your tree of FolderInfo structures.

Even though CTEs can express recursion, the GRDB query builder can not. Any given GRDB request executes a fixed number of SQL queries (1 + the number of including(all:) in the request), and can only build that many arrays.

For example, take a request with one including(all:):

let parentInfos = Parent
    .including(all: Parent.children)
    .asRequest(ParentInfo.self)
    .fetchAll()

It mechanically translates into the following code, which involves two SQL queries:

// Fetch parents
let parents = Parent.fetchAll(db)

// Fetch children
let children = Child
    .filter(parents.

Replies: 1 comment 2 replies

Comment options

You must be logged in to vote
2 replies
@seanmrich
Comment options

@groue
Comment options

Answer selected by seanmrich
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants