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

How do I query for two columns to be equal using Sequelize?

1个答案

1

In Sequelize, if you want to check whether two columns are equal in a query, you can use the Sequelize.where function and Sequelize.col method provided by the framework. This approach allows you to reference table columns within the where query condition and perform comparisons.

Here is a specific example. Suppose we have a model named Order with two fields: price and discounted_price. Now, we want to find all orders where price and discounted_price are equal.

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

In this example:

  • We import Op, where, and col from sequelize.
  • We use the Order.findAll() method to retrieve all records.
  • Within the where option, we use where(col('price'), Op.eq, col('discounted_price')) to specify that we want the value of the price column to equal the value of the discounted_price column.

This approach is relatively intuitive and can be conveniently used to compare two fields within the same model.

2024年8月9日 00:01 回复

你的答案