简体   繁体   中英

How to make a mysql “ladder” queries in nodejs with express

I'm having a problem, when I want to make a queries in "ladder" form with nodejs, express and mysql and return one json, It don't works for me, the structure of I want to make is:

select dev_id*,dev_name from devices
select cont_id*, cont_name from controllers where dev_id = dev_id
select act_id, acti_id from actions where cont_id = cont_id**

return json({devices,{controller,{actions}}})

I'm using forEach function and also I trying to use callback function.

You need to join all 3 tables, then loop through the results and build nested objects.

var mysql = require("mysql");
var con = mysql.createConnection({
  host: "localhost",
  user: "yourusername",
  password: "yourpassword",
  database: "mydb"
});
var sql = `SELECT d.dev_id, d.dev_name, c.cont_id, c.cont_name, a.act_id, a.acti_id
           FROM devices AS d
           LEFT JOIN controllers AS c ON c.dev_id = c.dev_id
           LEFT JOIN actions AS a ON a.cont_id = c.cont_id`;
con.connect(err => {
    if (err) {
        throw err;
    }
    conn.query(sql, (err, result, fields) => {
        if (err) {
            throw err;
        }
        var devices = {};
        $result.forEach(({dev_id, dev_name, cont_id, cont_name, act_id, acti_id}) => {
            devices[dev_id] = devices[dev_id] || {id: dev_id, name: dev_name, controllers: {}};
            devices[dev_id].controllers[cont_id] = devices[dev_id].controllers[cont_id] || {id: cont_id, name: cont_name, actions: {}};
            devices[dev_id].controllers[cont_id].actions[act_id] = {id: act_id, acti_id: acti_id};
        });
    });
    // do something with devices here
});

Remember that all the mysql query code is asynchronous, so you can't return values normally. You need to use callbacks or promises.

The devices variable will look like:

{
    devid1: {
        id: "devid1",
        name: "devname1",
        controllers: {
            contid1: {
                id: "contid1",
                name: "contname1",
                actions: {
                    actionid1: {
                        id: "actionid1",
                        acti_id: "acti_id1"
                    },
                    actionid2: {
                        id: "actionid2",
                        acti_id: "acti_id2"
                    }
                }
            },
            contid2: {
                id: "contid2",
                name: "contname2",
                actions: {
                    actionid3: {
                        id: "actionid3",
                        acti_id: "acti_id3"
                    }
                }
            }
        |
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM