SEQUELIZE:按相关模型的COUNT排序

时间:2018-06-09 00:31:51

标签: javascript sql json postgresql sequelize.js

我目前有一个返回Projects数组的查询,它还包含一个名为Campaign的模型。我的Campaign模型有一个名为status的列,可以是ACTIVEPAUSED。对于我的数组中的每个Project,我希望收到它包含的所有ACTIVE个广告系列的计数,然后我想根据该计数按降序排列我的Projects数组。

换句话说,我希望所有ProjectsACTIVE广告系列都显示在我的查询完成时收到的数组顶部。

const query = { id: { $in: ids } };

models.Project.findAndCountAll({
  where: query,
  limit: PROJECT_PAGE_SIZE,
  offset: (PROJECT_PAGE_SIZE * (pageNumber - 1)),
  distinct: true,
  attributes: Object.keys(models.Project.attributes).concat([
    [sequelize.literal('(SELECT SUM("strategies_data"."spend") FROM "strategies_data" WHERE "strategies_data"."project_id" = "Project"."id")'),
      'total_spend'],
    [sequelize.literal('(SELECT SUM("strategies_data"."impressions") FROM "strategies_data" WHERE "strategies_data"."project_id" = "Project"."id")'),
      'total_impressions'],
  ]),
  include: [{
    model: models.Campaign,
    attributes: ['id', 'name', 'status'],
    include: [{ model: models.Channel }, { model: models.Strategy }],
  }],
})

0 个答案:

没有答案