如何在ObjectionJS中检查QueryBuilder已添加指定关联关系
解决ObjectionJS动态查询重复关联报错的方案
方案一:手动维护已关联集合(推荐,稳定)
通过一个Set记录已添加的关联关系,每次操作前检查是否存在,避免重复执行leftJoinRelated:
// 初始化基础查询和关联追踪集合 const qb = Job.query(trx).select('id'); const joinedRelations = new Set(); // 封装安全添加关联的工具函数 const safeJoinRelated = (relation) => { if (!joinedRelations.has(relation)) { qb.leftJoinRelated(relation); joinedRelations.add(relation); } }; // 处理排序条件 if (body.sort) { safeJoinRelated('client'); qb.orderBy('client.name', body.sort); } // 处理过滤条件 if (body.filter) { safeJoinRelated('client'); qb.whereIn('client.clientGuid', body.filter); }
方案二:利用QueryBuilder内部属性(简洁,需注意版本兼容性)
ObjectionJS的QueryBuilder实例内部有_joinExpressions数组,存储了所有已添加的关联信息,可通过检查该数组判断是否已关联目标表:
const qb = Job.query(trx).select('id'); // 检查指定关联是否已添加 const hasJoinedRelation = (qb, relation) => { return qb._joinExpressions.some(expr => { return expr.relation?.name === relation; }); }; // 处理排序 if (body.sort) { if (!hasJoinedRelation(qb, 'client')) { qb.leftJoinRelated('client'); } qb.orderBy('client.name', body.sort); } // 处理过滤 if (body.filter) { if (!hasJoinedRelation(qb, 'client')) { qb.leftJoinRelated('client'); } qb.whereIn('client.clientGuid', body.filter); }
注意事项
- 方案一手动追踪的方式不受Objection版本更新影响,稳定性更高;
- 方案二依赖内部属性
_joinExpressions,如果Objection后续版本修改内部实现,可能需要调整判断逻辑。
内容的提问来源于stack exchange,提问作者search-learn
相关产品推荐
相关产品推荐

