Adonisjs嵌套插入

时间:2019-07-02 20:23:57

标签: javascript node.js

我最近从Express堆栈(TS + TypeOrm)切换到了Adonisjs。 我通过培训来构建小型应用,其中的关系看起来类似于:training 1:n exercise 1:n round

我使用TypeOrm在实体文件中描述了我的关系,配置如下:

运动性:

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

圆形实体:

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

它允许我通过提供JSON这样的方式“一次运行”保存所有嵌套记录:

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

,然后写: await getRepository(Training).create(training) <-培训只是请求的内容

它会自动将我的JSON与关系进行匹配,并且一切正常。


我如何使用Adonis做类似的事情?

型号:

Training.js

exercises () {
    return this.hasMany('App/Models/Exercise', 'id', 'training_id')
}

Exercise.js

training () {
    return this.belongsTo('App/Models/Training', 'training_id', 'id')
}
rounds () {
    return this.hasMany('App/Models/Round', 'id', 'exercise_id')
}

Round.js

exercise () {
    return this.belongsTo('App/Models/Exercise', 'exercise_id', 'id')
}

在控制器中,我以几个嵌套的forEach结尾。看起来像这样:

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

    const training = await Training.create({
        name: trainingData.name
    })

    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
            })
        })
    })

没有forEach(和exercises: trainingData.exercises),我会收到错误消息:

{
    "status": "error",
    "message": "Something went wrong",
    "err": {
        "name": "error",
        "length": 131,
        "severity": "ERROR",
        "code": "42703",
        "position": "55",
        "file": "parse_target.c",
        "line": "1005",
        "routine": "checkInsertTargets"
    }
}

我确定我错过了与人际关系的一个细节,我无法完成工作。

任何人都能以最好的方式帮助我吗?

非常感谢。

0 个答案:

没有答案