如何在Sequelize ORM中不使用原生语句查询有订单的客户
实现方法
前置要求:先配置模型关联
首先需要提前定义两个模型的一对多关联关系,参考代码:
const { Sequelize, DataTypes } = require('sequelize'); // 初始化sequelize实例逻辑省略 // 定义客户模型 const Customers = sequelize.define('Customers', { id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true }, name: DataTypes.STRING }, { timestamps: false }); // 定义订单模型 const Orders = sequelize.define('Orders', { id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true }, customerId: DataTypes.INTEGER }, { timestamps: false }); // 配置关联 Customers.hasMany(Orders, { foreignKey: 'customerId' }); Orders.belongsTo(Customers, { foreignKey: 'customerId' });
具体查询写法
通过设置关联查询的required: true实现INNER JOIN,同时配置去重参数即可达成需求,两种常用写法如下:
写法1:直接使用distinct参数
const result = await Customers.findAll({ attributes: ['name'], distinct: true, include: [{ model: Orders, required: true, // 开启后自动使用INNER JOIN,仅保留有匹配订单的客户 attributes: [] // 不返回订单表的任何字段,避免结果冗余 }], raw: true // 可选参数,开启后直接返回数据对象,不需要额外get()取值 });
写法2:用聚合函数包裹字段
const result = await Customers.findAll({ attributes: [[Sequelize.fn('DISTINCT', Sequelize.col('name')), 'name']], include: [{ model: Orders, required: true, attributes: [] }], raw: true });
两种写法生成的原生SQL和你给出的示例完全一致,不需要手动写任何SQL语句。
内容的提问来源于stack exchange,提问作者Rafael
相关产品推荐
相关产品推荐

