0

I could not get the a nested logic to work. I need to combined data from 2 table and return it to the request. I do not want a join table as I need to return an individual record from tableA first then combine with tableB record before it is returned. Below is my simplified code

exports.get_caution_reasons = async (req, res) => {
   let return_data = [];
   await db.sequelize.query("SELECT TableA xxxxx",{
                type: QueryTypes.SELECT
            }).then(recordA => {
                for (let index = 0; index < recordA.length; index++) {
                    return_data.push({recordA[index].xxx, recordA[index].yyy})
                    db.sequelize.query("SELECT TableB xxxxx WHERE zzz=recordA.zzz",{
                       type: QueryTypes.SELECT
                    }).then(recordB => {
                        for (let index = 0; index < recordB.length; index++) {
                            return_data.push({recordB[index].xxx, recordB[index].yyy}) 
                        }   
                    })
                }
                res.status(200).json({data: return_data});
            })
};

It only return the record for TableA only. I tried various async and await to get the recordB in there but without success. Any help is useful.

1 Answer 1

1

Probably something like that should work:

exports.get_caution_reasons = async (req, res, next) => {
    try {
        let options = { type: QueryTypes.SELECT }
        let data = []
        let result_a = await db.sequelize.query("SELECT TableA xxxxx", options)
        for (let index = 0; index < result_a.length; index++) {
            data.push({ /* whatever you need... */ })
            let result_b = await db.sequelize.query("SELECT TableB xxxxx WHERE zzz=recordA.zzz", options)
            for (let index = 0; index < result_b.length; index++) {
                data.push({ /* ... */ })
            }
        }
        res.json({ data })
    } catch (err) {
        next(err)
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.