在Sequelize ORM框架中加入无关联的查询

时间:2017-04-14 02:23:31

标签: sequelize.js

我可以在没有Seuqelize中定义的关联的情况下进行连接查询吗?

我尝试通过Sequelize

进行如下所示的SQL查询
updateInfo(arg)
{
    firstInfo = arg + "Info";
    console.log(firstInfo );
}

    updateInfo(firstInfo );

我在使用下面的findAll时使用添加的“include”确实做到了,我必须在使用include之前定义关联

Message.js

SELECT * FROM MessageRecipient INNER JOIN MESSAGE ON MessageRecipient.messageIdno = MESSAGE.Idno 

messageRecipient.js

var Message = sequelize.define('Message', {
 idno: {
  type: DataTypes.INTEGER,
  primaryKey: true,
  autoIncrement: true 
},
subject: DataTypes.STRING,
messageBody: DataTypes.STRING,
creatorId: DataTypes.INTEGER,
parentMessageId: DataTypes.INTEGER,
expiryDate:DataTypes.DATE,
isActive:DataTypes.INTEGER}, {
classMethods: {
  associate: function (models) { 
    Message.hasMany(models.MessageRecipient, { foreignKey: 'idno' });
  }}}); 
return ChatMessage;
};

findAll with include

var MessageRecipient = sequelize.define('MessageRecipient', {
 idno: {
  type: DataTypes.INTEGER,
  primaryKey: true,
  autoIncrement: true 
},
recipientId: DataTypes.INTEGER,
recipientGroupId: DataTypes.INTEGER,
messageId: DataTypes.INTEGER,
isRead:DataTypes.INTEGER
}, {
classMethods: {
  associate: function (models) { 
    MessageRecipient.belongsTo(models.Message, { foreignKey: 'messageId' });
  }
}
  }); return MessageRecipient;

我会得到我想要的查询结果

db.MessageRecipient
      .findAll({
        include: [{
          model: db.Message,
          required: true
        }]
      })
      .then((MessageRecipients) => {
        res.json(MessageRecipients);
      })
      .error((error) => {
        res.sendStatus(500);
      });

如果我没有在findAll之前定义关联,我将收到错误

[
  {
    "idno": 1,
    "recipientId": null,
    "recipientGroupId": 1,
    "messageId": 1,
    "isRead": 0,
    "createdAt": "2017-04-14T01:24:31.000Z",
    "updatedAt": "2017-04-14T01:24:31.000Z",
    "ChatMessage": {
      "idno": 1,
      "subject": "my message subject",
      "messageBody": "my message content here",
      "creatorId": 1,
      "parentMessageId": 0,
      "expiryDate": null,
      "isActive": 1,
      "createdAt": "2017-04-14T01:24:30.000Z",
      "updatedAt": "2017-04-14T01:24:30.000Z"
    }
  }
]

如何跳过hasmany,属于part并仍能获得如上所述的漂亮结果? 是否有解决方法可以做到这一点?

由于

1 个答案:

答案 0 :(得分:0)

我已经搜索了the documentation,但找不到指定您要加入的字段的方法。据我所知,无法通过条件查询来做到这一点。您要么要做单独的(效率低下)查询,要么就不得不使用原始查询:

sequelize.query('SELECT * FROM MessageRecipient INNER JOIN MESSAGE ON MessageRecipient.messageIdno = MESSAGE.Idno').then(([results, metadata]) => {
  // ...
})

该示例也来自the documentation