使用ANY运算符将SQL查询转换为Sequelize findAll函数时出现问题

时间:2019-05-14 10:03:48

标签: node.js postgresql sequelize.js inner-join

我有三个表:
1. posts(postId(PK),postTitle,postDescription)
2.广告活动(campaignId(PK),platformId(FK),effectiveFrom,effectiveThrough,postArray:postId [])
   //这里的postArray包含Integer类型的postIds
3. platform(platformId(PK),platformName)

,而我在PostgreSQL客户端上运行的查询是:

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);

返回以下输出:

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

现在,我想要在Sequelize中获得相同的输出,并且不确定如何在findAll函数中使用“任何”运算符。

这是我的findAll代码:

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});
    });
};

&这些是关系:

  db.campaigns.hasMany(db.posts,{sourceKey: 'postId', foreignKey: 'postArray'});
  db.campaigns.hasOne(db.platforms,{sourceKey: 'platformId', foreignKey: 'platformId'});

我知道我做错了,它不会运行。请为我提出解决问题的更好的方法。

1 个答案:

答案 0 :(得分:0)

Sequelize不支持通过数组的关系。通过使用include创建JOIN仅支持在sequelize中定义的关系,并且由于无法在sequelize中定义关系,因此是不可能的。