乐闻世界logo
搜索文章和话题

如何使用Sequelize查询两列是否相等?

1 个月前提问
24 天前修改
浏览次数6

1个答案

1

在Sequelize中,如果您希望在查询中检查两列是否相等,可以使用框架提供的Sequelize.where函数和Sequelize.col方法。这种方式允许您在where查询条件中引用表的列,并进行比较。

以下是一个具体的例子,假设我们有一个名为Order的模型,它有两个字段:pricediscounted_price。现在我们想要找出所有pricediscounted_price相等的订单。

javascript
const { Op, where, col } = require('sequelize'); const { Order } = require('./models'); async function findOrdersWithEqualPrices() { try { const orders = await Order.findAll({ where: where(col('price'), Op.eq, col('discounted_price')) }); return orders; } catch (error) { console.error('Error fetching orders:', error); } } findOrdersWithEqualPrices().then(orders => { console.log('Orders with equal prices:', orders); });

在这个例子中:

  • 我们从sequelize引入了Op, where, 和 col
  • 使用Order.findAll()方法来获取所有记录。
  • where选项中,我们使用where(col('price'), Op.eq, col('discounted_price'))来声明我们想要price列的值等于discounted_price列的值。

这种方法相对直观,并且可以很方便地用于比较同一个模型中的两个字段。

2024年8月9日 00:01 回复

你的答案