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
Bryan JimenezBryan Jimenez 

Help with Dynamic Soql Query

Hi, 
I am new to apex and I am trying to query a dynamic field but I cannot get it to work.

I have a field named "relationship lead" on a custom object named "Prospects".

I want to be able to query the records based on the relationship lead. Is that possible?
 
public class ClientRelationshipController {
 Public List<Prospect__c> getProspects() {
        List<Prospect__c> Prospects=[Select Name,Property__c,Property_Name__c,Phone__c,Mobile__c,Prospect_Score__c,Email__c,Relationship_Lead__c
                                     From Prospect__c 
                                     Where Created_Date__c = Yesterday 
                                     And RecordType__c = 'Prospect'
                                     And Relationship_Lead__c = 'Dynamic Field'];
        return Prospects;
      }

 }


 
Best Answer chosen by Bryan Jimenez
3 Creeks3 Creeks
To use a variable in your query you prepend a colon to it.  So if the variable holding the value of Relationship_Lead__c that you are looking up is "reLead", it would look like this:
 
List<Prospect__c> Prospects=[Select Name,Property__c,Property_Name__c,Phone__c,Mobile__c,Prospect_Score__c,Email__c,Relationship_Lead__c From Prospect__c Where Created_Date__c = Yesterday                                    And RecordType__c = 'Prospect'  And Relationship_Lead__c = :relLead];

 

All Answers

3 Creeks3 Creeks
To use a variable in your query you prepend a colon to it.  So if the variable holding the value of Relationship_Lead__c that you are looking up is "reLead", it would look like this:
 
List<Prospect__c> Prospects=[Select Name,Property__c,Property_Name__c,Phone__c,Mobile__c,Prospect_Score__c,Email__c,Relationship_Lead__c From Prospect__c Where Created_Date__c = Yesterday                                    And RecordType__c = 'Prospect'  And Relationship_Lead__c = :relLead];

 
This was selected as the best answer
Bryan JimenezBryan Jimenez
Hi 3 Creeks,

That helps me understand a bit more what i am doing.
How do I go about creating a variable that holds the values of the Relationship_lead__c Field? Because as of right now I get an error that says the variable does not exist, how would I create a variable which holds the ID's of the relationship_Lead__c field so that I can call it in my query?

Thank you again
3 Creeks3 Creeks
There are many, many ways, so it really depends on your design.  

If Relationship_lead__c is the id from another table, you could query that table and and then save the Id to the variable that is used in your Prospects query.  Somtimes Ids are part of a page's URL and you get them from there.  Sometimes it comes from a selection from a form that the user is on.

So the question is where does the value Relations_lead__c come from?