Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hierarchial SOQL Query

Does anyone know how to retrieve the hierarchical model of a account based on it's id?

I tried using this query but all i got is the first set of child nodes.

select a.Name,a.parentId,a.ownerid,a.id from  Account a where Parent.id ='00711314'
like image 378
karthick Avatar asked Dec 08 '25 22:12

karthick


2 Answers

SOQL does not support hierarchical retrieval, you have to retrieve level by level, for each level generate a list of id's and then retrieve next level using in <list> where operator.

Keep in mind though that governor limitations apply and if you have large trees you'll run into a limit quite easily.

like image 86
mmix Avatar answered Dec 11 '25 11:12

mmix


As already stated you can not make use of hierarchical retrieval with SOQL. When I've needed this functionality with other objects (and when I know there are < 10k rows) I've selected all records, then used a map of lists to build up the hierarchy in memory instead:

map<id, list<id>> mapParentToChildren = new map<id, list<id>>();

for(Record__c [] sRecordArr : [select Id, Parent__c from Record__c limit 10000])
{
    for(Record__c sRecord : sRecordArr)
    {
        if(mapParentToChildren.get(sRecord.Parent__c) == null)
        {
            mapParentToChildren.put(sRecord.Parent__c, new list<id>{sRecord.Id});
        }
        else
        {
            mapParentToChildren.get(sRecord.Parent__c).add(sRecord.Id);
        }
    }
}

You can then make use of a recursive function to perform operations etc. on the data, for instance (untested):

// top level records will have a null parent, so be in the 'null' list
for(id idRecord : mapParentToChildren.get(null))
{
    PrintTree(idRecord, 0);
}

public void PrintTree(id idRecord, int iLevel)
{
    string strLevel = '*';

    for(integer i = 0; i < iLevel; i++)
    {
        strLevel += '*';
    }

    System.Debug(strLevel + idRecord);

    if(mapParentToChildren.get(idRecord) != null)
    {
        for(id idChild : mapParentToChildren.get(idRecord))
        {
            PrintTree(idChild, iLevel + 1);
        }
    }
}

This code is inefficient and untested (I've just written this version straight into the browser) but it should give you an idea of how you can deal with hierarchical data on the platform.

like image 30
Matt Lacey Avatar answered Dec 11 '25 11:12

Matt Lacey



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!