如何在node.js中有多个关联/条件/包含在findAll上的sequelize

时间:2015-01-06 18:17:10

标签: javascript mysql node.js select sequelize.js

我有一个mysql数据库,我通过node.js中的sequelize访问。

我想加入3张桌子。

关系是:

Person n : n Work (associated through PersonWork having foreign key for Person and Work)
Work n : n Book (associated through BookWork having foreign key for Book and Work)

我想加入Person,Work和Book。

现在我在节点中嵌套2个查询,但结果似乎相当慢。

SQLPersonWork.findAll({ where: {}, include: [SQLWork, SQLPerson] }).success(function (sqlresult) {
    sqlresult.forEach(function ProcessPersonWorkResult(oneresult) {
        var work = oneresult.work;
        var name = oneresult.person.name;
        (function (work, name) {
            SQLBookWork.findAll({ where: { "work_id": work.id }, include: [SQLBook] }).success(function (sqlbookresult) {
                sqlbookresult.forEach(function ProcessBookResult(onebook) {
                    // process result I want to get
                });
            });
        })(work, name);
    });

您可以看到双嵌套的findAll()。

有没有办法将它合并为1个查询?

1 个答案:

答案 0 :(得分:0)

我不知道这是否是唯一的答案..

根据NodeJS Sequelize and FindAll with Include and constraintsnode.js sequelize associations, include on condition这似乎是不可能的,如果没有直接sql - 虽然这种似乎违背了续集的目的。

var qstring = "SELECT * FROM mydb.person p \
    join mydb.personrole pr on p.id = pr.person_id \
    join mydb.work w on w.id = pr.work_id \
    join mydb.bookwork bw on bw.work_id = w.id \
    join mydb.book b on b.id = bw.book_id;";
sequelize.query(qstring).success(function (result) {
    console.log(result.count);
    result.forEach(function ProcessRatingResult(oneresult) {
        console.log(oneresult);
    });
});

这也快得多。