+ Start a Discussion
isalewisalew 

Dot Notation vs. SOQL Query

I have a custom object LeadCompany__c to associate related leads.

Can I use dot notation to pull a list of all leads associated with my custom object, rather than use an SOQL query?

Currently, I must use the following query:

List<Lead> Lds = [SELECT ID FROM Lead WHERE LC_Lead_Company__c = :ld.LC_Lead_Company__c];

Would it be possible to get this information without an SOQL query in the following manner:

List<Lead> leads = ld.LC_Lead_Company__c.Leads;
 
sfdcfoxsfdcfox
In Apex Code, you must always explicitly query the data in order to obtain that information. There is no "magic" that allows you to bypass this. Note, however, in Visualforce, if you use the standard controller (e.g. for your custom object), you can auto-query the data, like this:

    <apex:page standardController="LeadCompany__c">
        <apex:repeat value="{!LeadCompany__c.Leads__r}" var="Lead">
            <apex:outputText value="{!Lead.Name}" />
        </apex:repeat>
    </apex:page>

In other words, your specific use case will depend on what you're attempting to accomplish. However, this still generates a query, it just happens to be a query generated by the platform's auto-query behavior instead of explicitly querying the data yourself.
Peter_sfdcPeter_sfdc
The assignment you show:

List<Lead> leads = ld.LC_Lead_Company__c.Leads;

is not technically valid as accessing the related records for custom relationships is always done using the __r syntax, like this:

List<Lead> leads = ld.LC_Lead_Company__r.Leads__r;

The big question is this: have you (or some other process) already populated Leads__r elsewhere? If something else has passed you a fully constructed list of related leads for LC_Lead_Company__c, you might be in business.

But even then, you still might not have all the field values. 

Requerying ensures you have all the data you will need to read. For instance, perhaps you need Lead.Status. If that wasn't queried previously, your query ensures it is now. 

Also, don't forget you can also do subqueries and relationship queries. So for instance, you could do this: 
 
LC_Lead_Company__c leadCo = [select Id,Name, (select Id, Name, Status from Leads__r)
from LC_Lead_Company__c
where id = : ld.LC_Lead_Company__c]; 

You would then be able to access the related lead list as well as whatever fields in your Lead_Company__c record. 
 
List<Lead> leads = leadCo.Leads__r; 
String name = leadCo.name; 


In general, if you're going to make a trip to the DB, think ahead if you might need to make a trip for a related record. If the answer is 'yes', then have a go at the relationship query.