I have three tables given as :
1. posts(postId(PK), postTitle, postDescription)
2. campaigns(campaignId(PK), platformId(FK), effectiveFrom, effectiveThrough, postArray: postId[])
// Here postArray contains postIds of Integer type
3. platforms(platformId(PK), platformName)
and the query I'm running on PostgreSQL Client is:
select posts.*, platforms.*, campaigns.campaignId, campaigns.platformId, campaigns.postArray
from campaigns
INNER JOIN platforms
ON campaigns.platformId = platforms.platformId
INNER JOIN posts
ON posts.postId = ANY(campaigns.postArray);
which returns the following output:
postid posttitle postdescription platformid platformname campaignid platformid postarray
1 Post1 This is Post1 1 Facebook 1 1 {1,2,3}
2 Post2 This is Post2 1 Facebook 1 1 {1,2,3}
3 Post3 This is Post3 1 Facebook 1 1 {1,2,3}
2 Post2 This is Post2 1 Facebook 2 1 {2,4,5}
4 Post4 This is Post4 1 Facebook 2 1 {2,4,5}
5 Post5 This is Post5 1 Facebook 2 1 {2,4,5}
2 Post2 This is Post2 3 LinkedIn 3 3 {2,3,4,5}
...
Now I want the same output in Sequelize and not sure how to use 'Any' operator in findAll function.
This is my findAll code:
exports.findAll = (req, res, next) => {
Campaigns.findAll({
include: [
{
model: Platform,
required: true
},
{
model: Post,
required: true,
[Op.any]: ['"postArray"']
}
],
order:[
['"campaignId"', 'ASC']
]
})
.then(campaign=> {
res.status(200).json(campaign.sort(function(c1, c2){return c1.campaignId - c2.campaignId}));
})
.catch(err => {
console.log(err);
res.status(500).json({msg: "error", details: err});
});
};
& these are the relations:
db.campaigns.hasMany(db.posts,{sourceKey: 'postId', foreignKey: 'postArray'});
db.campaigns.hasOne(db.platforms,{sourceKey: 'platformId', foreignKey: 'platformId'});
I know I'm doing it wrong and it won't run. Kindly suggest me a solution and better approach to my problem.
Sequelize doesn't support relations via arrays. Creating JOINs by using include only supports relations defined in sequelize, and since one cannot define the relation in sequelize, it's not possible.