Sub topic 13
Creating Junction Records in Apex
This chapter assumes you know how to model a many-to-many relationship with a junction object, and that you can read basic Apex and SOQL. The examples use the Enrollment__c junction object between Course__c and Student__c. Both of its fields are master-detail relationships.
Why parents must exist first
Each master-detail field on a junction object is required. A junction record can't be saved without a value for both fields, and each value must be the Id of an existing parent record. Apex assigns an Id only after a successful insert, so the order of operations matters:
- Insert the two parent records.
- Read their Ids.
- Insert the junction record that points to both.
A single junction record
Course__c course = new Course__c(Name = 'Apex Basics');
Student__c student = new Student__c(Name = 'Ada Lovelace');
insert course;
insert student;
insert new Enrollment__c(Course__c = course.Id, Student__c = student.Id);After each insert, the in-memory course and student variables hold their new Ids. The junction record then uses them directly.
If you try to insert the Enrollment__c record first, or leave one field empty, the insert fails with a REQUIRED_FIELD_MISSING error.
Many junction records at once
Triggers and batch jobs run on many records at a time, so build a list and issue one DML statement. Don't put DML inside a loop, because a transaction allows a limited number of DML statements (150).
List<Student__c> students = new List<Student__c>{
new Student__c(Name = 'Ada Lovelace'),
new Student__c(Name = 'Grace Hopper'),
new Student__c(Name = 'Alan Turing')
};
Course__c course = new Course__c(Name = 'Apex Basics');
insert course;
insert students;
List<Enrollment__c> enrollments = new List<Enrollment__c>();
for (Student__c s : students) {
enrollments.add(new Enrollment__c(Course__c = course.Id, Student__c = s.Id));
}
insert enrollments;This uses three DML statements no matter how many students there are.
Linking to existing parents
Often the parents already exist. Query them, then create the junction records. Use a Map to avoid a query per record.
Course__c course = [
SELECT Id FROM Course__c WHERE Name = 'Apex Basics' LIMIT 1
];
Map<Id, Student__c> students = new Map<Id, Student__c>(
[SELECT Id FROM Student__c WHERE Name LIKE 'A%']
);
List<Enrollment__c> enrollments = new List<Enrollment__c>();
for (Id studentId : students.keySet()) {
enrollments.add(new Enrollment__c(Course__c = course.Id, Student__c = studentId));
}
insert enrollments;Handling failures
By default, a bulk insert is all-or-nothing. If one record fails, the whole statement fails and none are saved. To save the valid records and inspect the failures, use Database.insert with allOrNone set to false.
List<Database.SaveResult> results = Database.insert(enrollments, false);
for (Integer i = 0; i < results.size(); i++) {
if (!results[i].isSuccess()) {
for (Database.Error err : results[i].getErrors()) {
System.debug('Row ' + i + ' failed: ' + err.getMessage());
}
}
}The results list keeps the same order as the input list, so index i identifies the failing record.
Avoiding duplicates
Salesforce doesn't stop you from enrolling the same student in the same course twice. Each pair becomes a separate junction record. To prevent this, query the existing junction records first and skip pairs that already exist.
Set<String> existing = new Set<String>();
for (Enrollment__c e : [
SELECT Course__c, Student__c FROM Enrollment__c
WHERE Course__c = :course.Id
]) {
existing.add(e.Course__c + '-' + e.Student__c);
}
List<Enrollment__c> toInsert = new List<Enrollment__c>();
for (Student__c s : students) {
if (!existing.contains(course.Id + '-' + s.Id)) {
toInsert.add(new Enrollment__c(Course__c = course.Id, Student__c = s.Id));
}
}
insert toInsert;A common alternative is a text field on the junction object that holds a combined key, marked as unique.
Common errors
| Error | Cause | Fix |
|---|---|---|
| `REQUIRED_FIELD_MISSING` | A master-detail field on the junction is empty | Set both parent Ids before inserting |
| `INVALID_CROSS_REFERENCE_KEY` | The Id doesn't belong to the expected parent object, or the record was deleted | Check the Id and its object type |
| `TOO_MANY_DML_STATEMENTS` | DML inside a loop | Collect records in a list and insert once |
Exercise
You need to enroll 200 existing students in one course. The code loops over the students and calls insert on a new Enrollment__c inside the loop. Why is this a problem, and how do you fix it?
Show answer
Each insert inside the loop is a separate DML statement, so 200 students exceed the limit of 150 DML statements per transaction. Add each new Enrollment__c to a List<Enrollment__c> inside the loop, then call insert on the list once after the loop.