Join request without join in Sequelize ORM framework

Can I make a connection request without an association defined in Seuqelize?

I am trying to make an SQL query as shown below through Sequelize

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

I did this by adding an “include” when using findAll, as shown below, and I have to define associations before using include

Message.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;
};

messageRecipient.js

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;

findAll with include

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

And I would like to get the result of the query I want, as shown below

[
  {
    "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"
    }
  }
]

If I do not define associations before findAll, I will get an error

Unhandled rejection Error: ChatMessage is not associated to ChatMessageRecipient!

How can I skip hasmany, belong to a part and still get a nice result as above? Is there a workaround to do this?

thank

+8
source share
2

, , , , .

0

, . , . ( ) , :

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

.

0

Source: https://habr.com/ru/post/1674796/


All Articles