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
citydivercitydiver 

子オブジェクトへのInsert

主従関係のオブジェクトで、子オブジェクトにデータが追加された際に動作するトリガを作成中です。

現在テスト用のクラスを作成しているのですが、子オブジェクトへのレコードの追加でつまづいています。

 

親オブジェクトをParent__c、子オブジェクトをChild__cとするとして、 こんな感じに書いてみたのですが、

リレーションの項目(ParentName__c)に 書き込めず、エラーとなりました。

 

ParentNm=[select Name from Parent__c where ParentItem__c = 'parentitem1'][0].Name;

 

Child__c[] child = new Child__c[] {

  new K_Outai__c(ParentName__c = ParentName, ChildItem__c = 'childitem1')

  new K_Outai__c(ParentName__c = ParentName, ChildItem__c = 'childitem2')

};

insert child;

 

参照項目なので書き込めないのは理解できるのですが、レコードを追加する手段がどうにもわかりません。

ご教授のほど、宜しくお願いします。

KouheiKouhei

リレーションの項目にはName項目ではなく、親オブジェクトの内部IDをセットする必要があります。

 

私がテストメソッドを書くなら以下のように書きます。

(※掲示なさったソースコードのK_Outai__cの部分はChild__cの書き損じだと解釈しました)

 

Parent__c parent = new Parent__c(Name = 'parent');

insert parent;  //insertすることで内部IDがセットされる

 

Child__c[] children = new Child__c[] {

new Child__c(ParentName__c = parent.Id, ChildItem__c = 'child1');

new Child__c(ParentName__c = parent.Id, ChildItem__c = 'child2');

};

insert children;

 

 

これでいかがでしょうか?

citydivercitydiver

子オブジェクトを表示すると親オブジェクトのName項目が表示されるので、

Name項目で紐づいているものと勝手に思い込んでました。

 

教えていただいたコードで、問題なく実行できました。ありがとうございました。