在Objection.js中如何基于子元素进行数据筛选?
解决Objection.js筛选关联数据的问题
你当前用withGraphFetched给关联的_customer加筛选的写法,本质是对关联表做**左连接(Left Join)**后过滤,所以会返回所有委托单,只是不符合条件的customer字段为null。要实现「只返回归属客户XYZ的委托单」,需要过滤主表Mandate,确保只有关联到目标客户的记录才被保留,以下是几种可行方案:
方案1:使用withGraphJoined(推荐)
withGraphJoined默认采用内连接(Inner Join),只有当关联的客户存在且匹配条件时,才会返回对应的委托单,同时保留嵌套的数据结构:
const mandates = await MandateModel .query(db) .withGraphJoined('_customer(isCustomer)') .modifiers({ isCustomer(builder) { builder.where('key', custId); } });
方案2:使用joinRelated关联筛选
通过joinRelated手动做内连接,再筛选客户条件,最后用withGraphFetched获取完整嵌套结构:
const mandates = await MandateModel .query(db) .joinRelated('_customer') .where('_customer.key', custId) .withGraphFetched('_customer');
方案3:用whereExists子查询验证关联
直接通过子查询检查当前委托单是否关联到目标客户,精准过滤主表数据:
const mandates = await MandateModel .query(db) .whereExists((builder) => { builder.select(1) .from('customers') // 替换为你的客户表实际表名 .whereColumn('customers.id', 'mandates.customer_id') // 替换为实际的关联字段映射 .where('customers.key', custId); }) .withGraphFetched('_customer');
以上三种方案都能确保只返回属于客户XYZ的委托单,且customer字段不会出现null值,数据结构符合预期。
内容的提问来源于stack exchange,提问作者paul23
相关产品推荐
相关产品推荐

