Let’s Learn Adonis 5: Querying, Checking Existence, and Aggregating Relationships

We’ll be learning a little about what Adonis is, the prerequisites to get started, and how to create a new project.

Tom Gobich
2 min readMar 14, 2021

Checkout the complete “Let’s Learn Adonis 5” series here.

In the last lesson we spent some time going through various ways you can query data using the query builder. In this lesson, we’re going to be talking specifically about querying relationships.

Querying relationships is one area where the difference between querying with our Models and using the Database module is significant. Since the Database module doesn’t make use of our relationship definitions in our models it has no contextual information about our relationships. So, for this lesson, we’ll be specifically utilizing our Models to query our relationships.

Preloading / Eager Loading

Lucid provides a method on our Model’s query builder and instances called preload. This method will cover the vast majority of relationship querying you're going to need to do.

So, say we want to query all projects with all their tasks. We can this by calling our preload method. Then, we provide it the name of the relationship we want to preload, as it's defined in the Model.

import Project from 'App/Models/Project'const projects = await Project.query().preload('tasks')

Here we’re getting all our projects, and nested within each project will be that project’s tasks. The resulting data would end up looking something like this.

[{
name: "My Example Project",
tasks: [{
name: "Introductory Task",
// ... other task data
}]
// ... other project data,
}]

Filtering Relationship Data

What if we need to filter down the data on the relationship we’re preloading? For this, the preload method accepts a second argument. This second argument is a callback function that provides us our relationship's query. So, we can use this callback argument to filter, sort, or limit down our related data.

const projects = await Project.query()
.preload('tasks', (query) => query
.where('status_id', 1)
.orderBy('due_at', 'desc')
)

Here we’re again querying all our projects, however, this time we’re only going to get back tasks for each project that have a status_id of 1. Additionally, our project's tasks will be ordered descending by their due date.

Continue reading

--

--

Tom Gobich

Owner of Jagr, JavaScript developer, educator, PlayStation gamer, burrito eater.