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
wesnoltewesnolte 

Associating and using Objects and their associated object fields

Hello

 

I'm having a curious issue that I'm sure there's a more elegant solution for. As an example:

 

 

public class a { B bee = new B(); insert bee; a.b__c = bee.id; }

 

 I now cannot do something along the lines of
   
    a.b__r.name = 'test';

 
I have to either fetch the associated object fields via SOQL or associate the object directly  e.g.


    a.b__r = bee;


If I use this approach though and then 'insert a', the objects will no longer be related. Therefore I have to assign the id and then associate the relationship with the 'b' object if I wish to use the fields via their relationship with 'a'.

 

I know this is a strange situation, but I'm trying to maintain 'session' data and am doing this for persistence.

 

Any ideas about a more elegant solution?

 

Wes

 

 

aalbertaalbert

Using the relationships is more valueable for querying. If you are trying to insert records into several related objects, it is best if you set the related id in the proper lookup/master-detail field. In your scenario (as shown in your snippet)

 

  a.b__c = bee.id;

 

Then set all the other necessary fields on object a and insert/update.  I do not believe you can set related fields using the relationship, __r, syntax. 

 

If you are trying to consider all of these DML operations as a single transaction, throw an exception and apex will implicitly rollback.