How to access and manipulate linked models after load them in Controller

Hello everyone, I hope you’re doing great!
First of all, thank you so much for taking the time to respond to me.

I have a question that maybe is caused due that I’m good enough to understand this using javascript. I have a method within a controller that returns the element I’m looking for through the id, and I also want to load its related models to it.

I have the following example:

async show ({ params, request, response, view }) {
        const program = await Program.find(params.id)
        await program.load('modules.topics.subtopics.activities')

        return {data: program.modules}
    }

// The previous code returns: {} //Empty object

So, what I want to do is to have access to each of the related models of “Program”, so in this case a “Program” contains many “Topics”, each “Topic” contains many “Subtopics” and so on.

The thing I want to do is to iterate over all these models using a foreach loop for example. But I’m facing this issue: When I try to print the related model after loading it trough the .load() method. However “at that time” it only returns an empty object without the “Topics” in this case. However, if I instead return just the const program like this:


async show ({ params, request, response, view }) {
        const program = await Program.find(params.id)
        await program.load('modules.topics.subtopics.activities')

        return program
    }

// The previous code returns the program containing the nested models.

It actually returns the program and all the nested models with the data. It’s strange because I even tried to evaluate with If statements certain conditions such as: if (program.modules > 0). However, when I do that it takes the program.modules as if it was empty or was undefined.

Does anybody know why this happens and what I can do to have access to each of the nested models, and in the future, add values to each model.

Something specific that I want to achieve is to iterate each model and add a new value to each of them like this:

modelName.newValue = true

A real example:

program.modules.forEach((_module) => {
 _module.completed = true
})

// It's seems like this code is not even executed because as I mentiod before "at that time" program.modules "is empty or undefined".

Thanks again for the help!

I think you need to use the getRelated method.

https://adonisjs.com/docs/4.1/relationships#_retrieving_loaded_models_data_2