Return Related Record Post Saving Record in AdonisJS

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 -

// 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.

comments powered by Disqus