Save nested objects in cascade way

#1

Hello, I recently switched from Express stack (TS + TypeOrm) to Adonis. I’m very happy with all Adonis’ features, but I cannot solve one problem.

I build small app with trainings, where relationships look similar to this:
training 1:n exercise 1:n round

With TypeOrm I described my relationships in Entity files, with such configuration:

Exercise Enitity

@OneToMany(type => Round, round => round.exercise, {
    cascade: ['insert', 'update']
})

Round Entity

@ManyToOne(type => Exercise, exercise => exercise.rounds, {
    cascade: true,
    onDelete: 'CASCADE'
 })

etc.

It allowed me to save all of my nested records ‘in one run’ by provide JSON like:

{
  "name": "Training"
  "exercises": [
    {
       "name": "Exercise",
       "rounds": [
         {
           "reps": 5,
           "weight": 6
         },
         {
           "reps": 7,
           "weight": 8
         }
       ]
    }, etc...
}

and just write:
await getRepository(Training).create(training) <-- Training was just body of the request

It automatically matched my JSON with relationships and everything worked great.

How can I do similar thing with Adonis?
Now I ended with couple of nested forEach. It looks like this:

      const trainingData = request.only(['name', 'private', 'category', 'exercises'])

      const training = await Training.create({
        name: trainingData.name,
        private: trainingData.private,
        'user_id': user.id,
        'category_id': trainingData.category
      })

      trainingData.exercises.forEach(async (exercise) => {
        const exerciseContainer = await Exercise.create({
          name: exercise.name, 'training_id': training.id
        })

        exercise.rounds.forEach(async (round) => {
          await Round.create({
            reps: round.reps, weight: round.weight, 'exercise_id': exerciseContainer.id
          })
        })
      })

I’m sure that I missed one detail with relationships and I can’t get job done.

Anyone can help me with the best way to do this?

Thanks, Kamil

0 Likes