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
Austin Callaro 8Austin Callaro 8 

APEX Code Error

Hello,

I continue to recieve a Compile Error when using the APEX Trigger functionalitly.  Below is the error message along with the source code I am using.  Please advise what I am missing here.

Error: Compile Error: Didn't understand relationship 'Line_Items__r' in FROM part of query call. If you are attempting to use a custom relationship, be sure to append the '__r' after the custom relationship name. Please reference your WSDL or the describe call for the appropriate names. at line 4 column 31

trigger DeleteRestrictInvoice on Invoice__c (before delete) {

  // create a list of Invoices in Trigger.oldMap along with their Line Items
  List<Invoice__c> invoices = [Select i.Name, (Select Name From Line_Items__r)
                                 From Invoice__c i
                                Where i.Id IN :Trigger.oldMap.keySet()];

  // loop through the Invoices, attaching errors to those that have Line Items
  for (Invoice__c invoice : invoices) {
    if (!invoice.Line_Items__r.isEmpty()) {
      Trigger.oldMap.get(invoice.id).addError('Cannot delete Invoice with Line Items');
    }
  }
}
 
Gaurav_SrivastavaGaurav_Srivastava
Hi Austin,

You are using wrong relationship name "Line_Items__r" in SOQL query. To find the relationship name, go to object definition "Line Item" and check the Child Relationship Name on field. Append  the __r into child relationship name in SOQL.

Thanks,
Gaurav
Austin Callaro 8Austin Callaro 8
User-added image

I tried to locate the child, as I thought that may be the issue earlier but it's not listed in the Line Item Object page?
venkat-Dvenkat-D
Click on Invoice Master Detail field. in that look for Child Relationship Name
Mahesh DMahesh D
Hi Austin,

I agree with both Gaurav and Venky.

In addition to their answer, please follow the below link to know more about relationship queries:

https://developer.salesforce.com/docs/atlas.en-us.soql_sosl.meta/soql_sosl/sforce_api_calls_soql_relationships_understanding.htm

and how to identify the Parent and Child Relationship Names.

https://developer.salesforce.com/docs/atlas.en-us.200.0.soql_sosl.meta/soql_sosl/sforce_api_calls_soql_relationships_parent_child.htm#sforce_api_calls_soql_relationships_parent_child

Also please find the below screenshot to find the relationship:

 User-added image

Once you find the Child Relationship name, you can replace it in your existing query.

Regards,
Mahesh
Austin Callaro 8Austin Callaro 8
Thank you!!