You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

APEX不支持三级及以上关系查询的解决方案咨询

解决Salesforce三级SOQL子查询限制,构建Lightning Tree层级数据

Salesforce SOQL确实不支持超过两级的嵌套子查询,针对你的需求,推荐两种可行的解决方案:

方法一:分步查询+手动组装树结构

拆分两次查询获取数据,再手动构建符合Lightning Tree要求的层级结构:

  1. 查询当前Merchandise关联的Production Requests
// 传入当前页面的Merchandise recordId
List<Production_Request__c> prodRequests = [
    SELECT Id, Name /* 按需添加其他展示字段 */
    FROM Production_Request__c
    WHERE Merchandise__c = :recordId
];
  1. 查询关联的Purchase Requests
    提取Production Request的ID集合,用IN子查询批量获取对应的Purchase Requests:
Set<Id> prodRequestIds = new Set<Id>();
for(Production_Request__c prod : prodRequests) {
    prodRequestIds.add(prod.Id);
}

List<Purchase_Request__c> purchRequests = [
    SELECT Id, Name, Production_Request__c /* 关联Production Request的外键字段 */
    FROM Purchase_Request__c
    WHERE Production_Request__c IN :prodRequestIds
];
  1. 构建Lightning Tree节点数据
    用Map分组关联关系,再组装成树结构:
// 按Production Request分组Purchase Requests
Map<Id, List<Purchase_Request__c>> prodToPurchMap = new Map<Id, List<Purchase_Request__c>>();
for(Purchase_Request__c purch : purchRequests) {
    if(!prodToPurchMap.containsKey(purch.Production_Request__c)) {
        prodToPurchMap.put(purch.Production_Request__c, new List<Purchase_Request__c>());
    }
    prodToPurchMap.get(purch.Production_Request__c).add(purch);
}

// 组装树节点数组
List<Object> treeNodes = new List<Object>();
for(Production_Request__c prod : prodRequests) {
    Map<String, Object> prodNode = new Map<String, Object>{
        'label' => prod.Name,
        'value' => prod.Id,
        'children' => new List<Object>()
    };
    // 绑定子节点
    if(prodToPurchMap.containsKey(prod.Id)) {
        for(Purchase_Request__c purch : prodToPurchMap.get(prod.Id)) {
            prodNode.get('children').add(new Map<String, Object>{
                'label' => purch.Name,
                'value' => purch.Id
            });
        }
    }
    treeNodes.add(prodNode);
}

将treeNodes返回给LWC后,直接绑定到lightning-tree组件的items属性即可。

方法二:单次外连接查询+分组

如果Purchase Request、Production Request、Merchandise是链式外键关联(Purchase Request → Production Request → Merchandise),可以用一次外连接查询获取所有数据,再分组构建结构:

List<Purchase_Request__c> purchRequests = [
    SELECT Id, Name, Production_Request__r.Id, Production_Request__r.Name
    FROM Purchase_Request__c
    WHERE Production_Request__r.Merchandise__c = :recordId
];

后续同样用Map分组Production Request与对应的Purchase Requests,再组装成树结构即可。这种方式仅需一次查询,但需要确保外键字段的访问权限和API名称正确。

注意事项

  • 检查对象关系的API名称是否正确(比如你原SOQL中SELECT ID (SELECT...缺少逗号,正确格式应为SELECT Id, (SELECT...)
  • Lightning Tree要求每个节点必须包含label和value属性,children为可选子节点数组
  • 若数据量较大,需添加LIMIT限制或分页逻辑,避免超时

内容的提问来源于stack exchange,提问作者Suomynona

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.25 05:54:17