如何基于关联模型的关联模型字段添加Where查询条件?
问题:通过关联模型的嵌套字段过滤Application数据
我需要在查询中添加where子句,实现通过Application关联的Job所属的Company字段过滤结果。目前只能实现按Job表字段过滤,无法按更深层的Company字段过滤。
模型关联关系
Applicant.belongsToMany(Job, {through: Application}) Job.belongsToMany(Applicant, { through: Application }); // 关联配置以便直接查询Application表 Application.belongsTo(Job, { foreignKey: { name: 'jobId' }}); Application.belongsTo(Applicant, { foreignKey: { name: 'applicantId' } }); Company.hasMany(Job, { foreignKey: { name: 'companyId', allowNull: false} }); Job.belongsTo(Company, { foreignKey: { name: 'companyId', allowNull: false} });
现有Job字段过滤逻辑(可生效)
我当前能实现按Job的title字段过滤applications,代码如下:
const options = { order: // ... distinct: true, attributes //... include: [ { model: Job, include: [ { model: Company, attributes: [ 'id', 'name' ], include: [ { model: Contact, separate: true, include: [{ model: Person, attributes: [ 'firstName', 'lastName', 'phone', 'email' ] }] } ] } ] }, { model: Applicant, include: [ { model: Person, attributes: [ 'id', 'firstName', 'lastName', 'email', 'phone', 'createdAt' ] } ], } ]; } if(x) options.include[0].where = { title: { [Op.like]: `%${searchTerm}%` } }; const results = Application.findAll(options)
这段代码能返回job.title匹配searchTerm的applications,符合需求,但我怀疑这是巧合生效的错误写法。
尝试Company字段过滤的问题
当我尝试按Company的name字段过滤时,用类似逻辑添加了以下代码:
if(x) options.include[0].include[0].where = { name: { [Op.like]: `%${searchTerm}%` } };
结果是返回了所有applications,不符合条件的job和company会显示为null,这不是我想要的——我只需要company.name匹配searchTerm的applications。
自行找到的解决方案
后来我意识到混淆了嵌套where子句和顶层where中引用嵌套字段的语法,改用$nested.nested.column$写法后可以正常生效:
options.where = {'$job.company.name$': { [Op.like]: `%${searchTerm}%` }}
但我仍有疑问:之前按Job字段过滤的写法为什么能正常生效?
内容的提问来源于stack exchange,提问作者NickW
相关产品推荐
相关产品推荐

