2

I have a custom object Contract__c, which is in a relationship with Address__c. A Contract can have many Addresses, so Adress__c has a lookup field to Contract__c.

I am trying to query all the Addresses related to a contract, but I seem to be having difficulties:

SELECT Id, (SELECT Id FROM Address__c) FROM Contract__c

What am I doing wrong here?

3 Answers 3

4

You need to go by the relationship which is likely:

SELECT Id, (SELECT Id FROM Address__r) FROM Contract__c

In order to find the correct relationship name you can look here: How to find out relationships for SOQL queries?

EDIT: Expand your project and its on the bottom of Eclipse.

enter image description here

4
  • Ah, I just realised why it doesn't work It is because Address_c is a junction object. Does that make a difference? I tried appending __r, and it didn't work.
    – Lily
    Commented Dec 10, 2014 at 22:06
  • It's not necessarily just __r. You'll need to review the lookup field for the relationship name. In addition, based on which 'direction' you you plan to query, the Parent w/ Child query and the Children w/ Parent queries are written significantly different. THIS is your friend salesforce.com/us/developer/docs/dbcom_soql_sosl/Content/…
    – HomerJ
    Commented Dec 10, 2014 at 22:25
  • Thanks for that link! I have installed the Eclipse IDE, but can't quite find out how to access this schema thingy. How can I open it?
    – Lily
    Commented Dec 10, 2014 at 23:17
  • @Lily Edited with a screenshot showing where the schema is.
    – dphil
    Commented Dec 11, 2014 at 14:45
1

In Relationship Queries For parent-to-child relationships, the parent object has a name for the child relationship that is unique to the parent, the plural of the child object name.

In your case, the query should be:

SELECT Id, (SELECT Id FROM Addresses__r) FROM Contract__c

Let me know whether it works.

0
0

Address__r is the relationship name of the Address__c to Contract__c

newAddress is holding all the value of Address__c from trigger.new, So if you have a list of Address then you can use that List of Address instead of newAddress this query will return the Contract related to all Addresses

List<Contract__c> conList = [Select Id,(Select Id from Address__r) from Contract__c where Id IN (Select Address__c from Address__c where Id IN :newAddress)];

If you want to query for single address then simply write the condition for the address in where Clause like:

List<Contract__c> conList = [Select Id,(Select Id from Address__r) from Contract__c where Id IN (Select Address__c from Address__c where Id = '0092813000vzvu1')];

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .