Sample Relationship Queries

Sample Relationship Queries in Salesforce

Updating Child - parent Relationship for standard objects:

list<Contact> c=“Select LastName, Account.Name From Contact where name like '%red%'“;

for(Contact ct : c)

{

ct.Account.Industry='Banking'; ct.account.Rating = 'Hot'; update c.account;

}

 Updating parent - Child Relationship for standard objects:

List<Account> a = “Select Name,(Select FirstName,LastName from Account.Contacts) From Account where Name='Account1'“;

System.debug('The Account Records are' +a);

for(Account acc1:a)

{

for(Contact c:acc1.Contacts)

{

c.FirstName='Anil';

c.lastName='Reddy';

update c;

System.debug ('The Updated Contacts are' +c);

}

}

Fetching Child - Parent Relationship for Custom objects:

Patient__C pt = “select name , medical__r.name from patient__C where id='a0190000002wRdn'“;

System.debug('Patient Records '+ pt);

System.debug('Doctor Records '+pt.medical__R.Name);

list<patient__C> pt = “select name , Medical__r.name from patient__C where name like 'sath%'“;

System.debug('Patient Records '+ pt); for(patient__c pt1 :pt)

{

system.debug('medical Records Are ' + pt1) ;

}

Aspired to become an Salesforce? Explore the post to discover the know-hows on Salesforce Training and Architecture.

Updating Child - parent Relationship for Custom objects:

Patient__C pt = “select name , medical__r.name from patient__C where id='a0190000002wRdn'“;

System.debug('Patient Records '+ pt); pt.medical__r.med_quantity__C = 66; update pt.medical__r;

System.debug('Medical Name '+pt.medical__r.Name); System.debug('Medical quantity '+pt.medical__r.med_quantity__C);

 For Multiple Records:

list<patient__C> pt = “select name , Medical__r.name, medical__r.med_quantity__C from patient__C where name = 'sateesh'“;

System.debug('Patient Records '+ pt); for(patient__c pt1 :pt)

{

pt1.medical__r.med_quantity__C = 99; update pt1.medical__r;

system.debug('medical Records Are ' + pt1) ;

}

 Fetching parent - Child Relationship for Custom objects:

Medical__c t=“Select Name,(Select Name from patients__r) From Medical__c

where id='a0290000005FUJq'“;

System.debug('XXXXXXXXXXXX'+t);

System.debug('DDDDDDDDDDDDDD'+t.patients__r);

for(medical_ _c s:t.patients__r)

{

System.debug(s.Name);

}

For Mulitiple Records:-

List<Training__c> t=“Select Name,(Select Name, Student_fee__c from Students__r) From Training__c “;

for(Training__c t1:t)

{

System.debug(t1.Name);

}

for(List<Student_ _c s:t1.students_ _r)

{

System.debug('AAAAAAAAAA'+s);

}

For indepth understanding on Salesforce click on