To access parent fields through sObject class methods, you can use the getsObject
method to get the parent record as an sObject, and then use the get method to get the value of a specific field.
For example, you can use the following code to access the Account Name and Rating fields from the Opportunity record:
List<Sobject> oppty = [SELECT Id, StageName, Account.Name, Account.Rating
FROM Opportunity WHERE Name = 'Sample' AND CloseDate = :DateToday];
// Get the first opportunity record from the list
SObject opp = oppty[0];
// Get the account record as an SObject
SObject acc = opp.getSObject('Account');
// Get the account name and rating as strings
String accName = (String) acc.get('Name');
String accRating = (String) acc.get('Rating');
system.debug('accName :: '+accName);
system.debug('accRating :: '+accRating);
To update parent object fields using the above query, you can use the put method to set the value of a specific field, and then use the update statement to save the changes to the database.
For example, you can use the following code to update the Account Rating field to 'Hot':
List<Sobject> oppty = [SELECT Id, StageName, Account.Name, Account.Rating
FROM Opportunity WHERE Name = 'Sample' AND CloseDate = :DateToday];
// Get the first opportunity record from the list
SObject opp = oppty[0];
// Get the account record as an SObject
SObject acc = opp.getSObject('Account');
// Set the account rating to 'Hot'
acc.put('Rating', 'Hot');
// Update the account record in the database
update acc;
String accName = (String) acc.get('Name');
String accRating = (String) acc.get('Rating');
system.debug('accName :: '+accName);
system.debug('accRating :: '+accRating);