【问题标题】:Sequelize filter for properties of hasMany association in where clause在 where 子句中对 hasMany 关联的属性进行 Sequelize 过滤器
【发布时间】:2020-10-27 15:34:15
【问题描述】:

我有以下型号:

const Machine = sequelize.define('Machine', { name: DataTypes.STRING });
const Review = sequelize.define('Review', { ReviewDate: DataTypes.DATEONLY });

Review.belongsTo(Machine);
Machine.hasMany(Review);

现在我想获取最后审查日期超过 3 个月的所有机器。

const reviewOverdueDate = new Date();
reviewOverdueDate.setMonth(reviewOverdueDate.getMonth() - 3);

const request = {
  include: [{
    model: Review,
    order: [
      ["ReviewDate", "DESC"]
    ],
    limit: 1
  }],
  where: {
    // this obviously does not work, because the included Review is an array
    // but maybe there is some syntax to access the first entry in that array?
    '$Review.ReviewDate$': { [Op.gt]: reviewOverdueDate }
  }


Machine.findAndCountAll(request)

如何编写适当的 where 子句来实现目标?有没有办法使用$nested.column$ 语法来访问列表/数组?

我让它在 where 子句中使用 sequelize 文字

where: {
  Sequelize.literal(`('${reviewOverdueDate.toISOString()}' > (SELECT "ReviewDate" FROM 
  "Review" WHERE "Review"."MachineID" = "Machine"."ID" ORDER BY 
  "Review"."ReviewDate" DESC LIMIT 1))`)
}

但我喜欢用 sequelize 表示法并使用 hasMany 关联。

【问题讨论】:

    标签: node.js postgresql sequelize.js associations eager-loading


    【解决方案1】:

    您是否尝试过在 de include 中使用 where 子句?

    const request = {
      include: [{
        model: Review,
        order: [
          ["ReviewDate", "DESC"]
        ],
        limit: 1,
        where: {
          ReviewDate: { [Op.gt]: reviewOverdueDate }
        }
      }]
    

    【讨论】:

      猜你喜欢
      • 2014-11-07
      • 2014-11-02
      • 2019-02-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-08-18
      • 2021-09-27
      相关资源
      最近更新 更多