This page looks best with JavaScript enabled

Return Related Record Post Saving Record in AdonisJS

 ·   ·  ☕ 1 min read

AdonisJS automatically returns the base/parent record to the caller from the controller. However, you may have to custom code all of one statement to return a related record after the parent record is committed to the database.

Consider an example -

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
// TodoController.js
async create({ request, auth }) {
    const user = await auth.getUser();
    const data = request.all();

    const todo = new Todo();
    todo.fill(data);
    // commit todo and any related entities sent
    // through data to the database

    await todo.save();
    // this will populate any changes made by Adonis/DB

    await todo.load("user"); // user is related entity
    // query and popular user entity within todo
    // follows same serializer as rest of the application

    return todo;
}

When you create a Todo, the controller takes the data sent in the request and commits that to the database. Post commit todo variable will have the data from database after committing the data.

You have to do a load and specify entities that need to be refreshed and included in todo along with the parent record. The newly updated todo variable with parent and related records will be returned to the caller.

Stay in touch!
Share on

Prashanth Krishnamurthy
WRITTEN BY
Prashanth Krishnamurthy
Technologist | Creator of Things