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.
javascriptconst { 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, andcolfromsequelize. - We use the
Order.findAll()method to retrieve all records. - Within the
whereoption, we usewhere(col('price'), Op.eq, col('discounted_price'))to specify that we want the value of thepricecolumn to equal the value of thediscounted_pricecolumn.
This approach is relatively intuitive and can be conveniently used to compare two fields within the same model.
2024年8月9日 00:01 回复