如何在node.js中使用sequelize编写mysql连接查询?

时间:2017-09-04 04:36:06

标签: node.js sequelize.js

让我们说我有一个像这样的MySQL表:

enter image description here

如何使用sequelize编写以下MySQL查询?

select mt.JobId 
from   MyTable as mt join MyTable as mt2 on mt2.JobId = mt.JobId
where  mt.TaskSeq = 0 and mt.TaskState = 'Done' and mt2.TaskSeq = 1 
and mt2.TaskState = 'New'

此查询返回JobId处于taskA状态且Done处于taskB状态的所有New

在这种情况下,它会返回qwertzxcv

阅读类似的stackoverflow问题here之后。我有点困惑,因为我只有一张桌子。我应该使用hasManybelongsTo来在sequelize中创建join查询吗?

以下是我用于创建此表的node.js脚本的一部分

var MyTable = conn.define(
'MyTable',
{
    JobId: {
    type: Sequelize.STRING,
    unique: true
    },
    TaskName: {
    type: Sequelize.STRING
    },
    TaskSeq: {
    type: Sequelize.INTEGER
    },
    TaskState: {
    type: Sequelize.STRING
    }
},
{
    collate: 'utf8mb4_bin'
}
)

MyTable.sync()
module.exports = {
    MyTable, conn
}

这是我的续集查询,无法返回我需要的JobId

MyTable.belongsTo(MyTable, {foreignKey: 'id'})
MyTable.findAll({
attributes: ['JobId'],
where: {
    TaskSeq: 0,
    TaskState: 'DONE'
},
include: [{
    model: MyTable,
    attributes: ['JobId'],
    where: {
        JobId: sequelize.col('MyTable.JobId'),
        TaskSeq: 1,
        TaskState: 'NEW'
    }
}]
}).then(result => {
    console.log(result)
})

2 个答案:

答案 0 :(得分:0)

是的,您需要定义关联,以便查询中的include函数有效。 http://docs.sequelizejs.com/manual/tutorial/associations.html

你的MyTable.belongsTo(MyTable,{foreignKey:' id'})是不是使用了正确的ID呢?如果您想加入JobId,请使用它。我上面的表格中甚至没有看到并标识列。

或尝试原始查询:

`sequelize.query('select mt.JobId from MyTable as mt join MyTable as mt2 on 
   mt2.JobId = mt.JobId where mt.TaskSeq = 0 and mt.TaskState = 'Done' and 
   mt2.TaskSeq = 1', { type: sequelize.QueryTypes.SELECT }
 ).then(myTables => {
   console.log(myTables)
 })`

答案 1 :(得分:0)

如果您的模型与其他表有关联,您可以执行以下操作:

var Product = sequelize.define('Product',{
        name: {
            type: DataTypes.STRING,
            field: 'description'
        }
    },{
        classMethods: {
            associate : function(models) {
                Product.belongsTo(Category,{
                    as: 'category',
                    foreignKey: {
                        allowNull: false
                    },
                    onDelete: 'CASCADE'
                });
            }
        }
    });


Product.findAll({
  include: [{
   model: Category,
   as: "category"     
  }]
})

结果将是:

{
 id:1,
 name:'product1',
 category: {
  id:23,
  name: 'category1'
 }
}