"WHERE" 嵌套 table 的 Sequelize 子句

"WHERE" clause in Sequelize with nested table

在我的私人项目中使用 Sequelize 期间,我有一个 table

const Order= sequelize.define('Order', {
    _id: {
        type: DataTypes.INTEGER,
        primaryKey: true,
        autoIncrement: true
    },
    value: {
        type: DataTypes.INTEGER,
        allowNull: false
    },
    _order_tracker_id: {
        type: DataTypes.INTEGER,
        allowNull: true
    },
    type: {
        type: DataTypes.INTEGER,
        allowNull: false
    },

Order.associate = function(models) {
    const {Order} = models
    
    Order.hasMany(Order, {
      as: 'tempOrder',
      foreignKey: '_order_tracker_id',
      onDelete: 'RESTRICT',
      onUpdate: 'RESTRICT'
    })
    
  }

});

我正在使用 Sequelize 查询数据:

const { Order} = sequelize.models
const oSequelize = {
      attributes: [
        '_id',
        'value',
      ],
      raw: false,
      include: [
        {
          model: Order,
          as: 'tempOrder',
          attributes: ['value' as 'tracker_value'],
          where: {
            [Op.or]: [
              {
                value: {
                  [Op.gt]: 1
                }
              },
              {
                '$tempOrder.value$': { [Op.gt]: 1 }
              }
            ]
          },
          required: false
        },
      ],

我希望它会显示与此相同的结果 SQL:

SELECT T1._id, T1.value, T1._order_tracker_id, T2.value as tracker_value 
FROM Order as T1 
JOIN Order as T2 ON T1._id = T2._order_tracker_id
WHERE T1.type = 1 AND (T1.value > 1 OR T2.value > 1)

更多解释:比如我有这个table

_id   value     _order_tracker_id  type
1     100        null              1
2     0          null              1
3     300        2                 2

为了在 UI 中显示数据,我希望我的查询结果是这样的

_id    value    _order_tracker_id     tracker_value
1      100      null
2      0        null                   300

我卡的地方是:不知道怎么把(T1.value > 1 OR T2.value > 1)转成sequelize语法。 如何更改 Sequelize 配置以达到预期结果?

我在这里展示了这个例子,请试试这个。希望对您有所帮助。

谢谢

const { Order} = sequelize.models
const oSequelize = Table1.findAll({
  attributes: [
    '_id',
    'value',
  ],
  raw: false,
  where: {
        [Op.or]: [
          {
            value: {
              [Op.gt]: 1
            }
          },
          {
            '$table2.value$': { [Op.gt]: 1 }
          }
        ]
      },
  include: [
    {
      model: Table2,
      as: 'table2',
      attributes: ['value' as 'tracker_value'],
      required: false
    },
  ]

})