In this blog post, we’ll explore the concept of related records in Salesforce and delve into our understanding of SOSL in Apex.
What do we mean by Related Records in Apex?
Adding Related Records
Illustration:
Account acc = new Account(Name=’abc’, Phone = ‘123456’); insert acc; Contact con = new Contact(Account=acc.Id, FirstName = ‘abc’ , LastName = ‘xyz’, Phone = ‘12345’); Insert con;
Modifying Related Records
Contact con = [SELECT Id, Name,Account.Phone FROM Contact WHERE Name = ‘abc’ AND AccountId!=Null AND Account.Name = ‘Account1’]; Con.Phone=’111’; Con.Account.Phone=’2222’; update con; update con.Account;
Now, let’s transition to SOSL!
What does SOSL mean in the context of Apex?
- SOSL stands for Salesforce Object Search language.
- It is used to perform a text search in records.
- We can use SOSL to search fields across multiple sObjects records.
- SOQL is used to retrieve records for a single object whereas use SOSL to search fields across multiple objects.
Syntax Structure
Find ‘SearchQuery’ [IN SearchGroup] [RETURNING ObjectsAndFields];
What constitutes a Search Query?
- Single Word: It should be enclosed in single quotes.
- Phrase: It is having multiple words and should be enclosed in double quotes.
What defines a Search Group?
SearchGroup is optional.
- The default is ALL FIELDS.
- You can choose from the following search groups:
- ALL FIELDS
- NAME FIELDS
- EMAIL FIELDS
- PHONE FIELDS
- SIDEBAR FIELDS
Objects and their Fields
- bjectsAndFields is optional.
- It is the information to return in the search result – a list of one or more sObjects and within each sObject, list of one or more fields, with optional values to filter against.
- If not specified the search result contain the IDs of all objects found.
Anonymous Execution Window
List<List<sObject>> searchList = [FIND ‘Cloud’ IN ALL FIELDS RETURNING Account(Name),Contact(FirstName, Lastname, Email)];
Query Console
FIND {Cloud} IN ALL FIELDS RETURNING Account(Name), Contact(FirstName, LastName, Email)];
As an illustration
List<List<sObject>> searchList = [FIND ‘Abc’ IN ALL FIELDS RETURNING Account(Name), Contact(FirstName,LastName,Email)]; List<Account> accList = new List<Account>(); List<Contact> conList = new List<Contact>(); accList = (List<Account>) searchList[0]; conList = (List<Contact>) searchList[1]; for(Account acc : accList) { System.debug(‘Name =>' + acc.Name); } for(Contact con : conList) { System.debug(con.FirstName + ‘ ‘ + con.LastName); }
That covers the topic of related records in Apex and SOSL. I trust this information proves valuable to you.