function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Bhargav SurapaneniBhargav Surapaneni 

self lookup getting all the parent records from child record

Hi,
I have a scenario where I need to count the number of the parent records( in the hierarchy) from child records in trigger.

But we don't know how many parent records are existing for a child.

Could you please help in approaching this using trigger on after insert.

Thanks in advance
 

Adilson Arcoverde JrAdilson Arcoverde Jr
Hi Bhargav,

Assuming you don't have an account with more than 100 generations above (parents), you could try the following code in your trigger.
 
    public static Integer getParentsCount( Account acc, Integer currentCount ) {
		
		if( acc.ParentId != null ) {
			currentCount += 1;
			Account parentAcc = [Select Id, ParentId from Account where Id = :acc.ParentId];
			return getParentsCount( parentAcc, currentCount );
		} 
		return currentCount;
	}

Best regards.