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
RyanhRyanh 

Something about object relationships I don't get (newbie)

I have a controller extension class for a VisualForce page using a custom object as the standard controller.

 

The custom object, an "Insertion Order" has a master-detail relationship to the Opportunity it belongs to. The constructor instantiates an object "io" with the "stdController.getRecord()" call.

 

In a method in the extension class (IOHelper) I'm trying to get the Account that the Opportunity belongs to, but I'm just not getting the relationships concept apparently.

 

Here are the results of a series of debug statements:

 

 

System.debug(io.Opportunity__c); // output=006R0000003JrLn (expected)System.debug(io.Opportunity__c.Name); // won't compile; "Invalid foreign key relationship"System.debug(io.Opportunity__r.Account); // nullSystem.debug(io.Opportunity__r.AccountId); // nullSystem.debug(io.Opportunity__r.Account.Id); // null

 

 what gives? what am I doing wrong?

 

I don't really understand where the "__r" syntax fits in, but it doesn't compile with "__c" 

werewolfwerewolf

Depending on the context in which you're running your Apex code, you may have to query for that information specifically for it to be populated.  Just getting the object will get you the information about the object itself but not necessarily about data it references.

 

So, provided you've already populated the io variable as you have, if you were to do something like

 

Insertion_Order__c io2 = [select  io.Opportunity__r.AccountId, io.Opportunity__r.Account.Name from  Insertion_Order__c io where Id=:io.Id];

 

Then you could retrieve the information you want using these references from io2.

 

Of course, if the AccountId is genuinely null (as it would be for a brand new object, say), then you'll get null for these values.