I have two related objects example Teacher and Student. Inside my parent object Teacher I have a field maximum_number_of_student.What I want is that if I add a new student the code will check if I exceed the maximum_number_of_student of the parent object. If not, new student will be added else the system will give an error that the number of student exceed for the certain teacher. What is the best way to do it ? Please help. Thank you...

  • You might get away with Roll Up summary and a validation rule something like this teacher__r.count_of_total_students__c > teacher__r.maximum_number_of_student__c.
    – dzh
    Dec 1 '15 at 11:08

I not sure if you have master detail relationship. But you can do this in trigger. Using inner query.

List<User> users = [SELECT Name, (SELECT id FROM Applications__r) FROM User];
for (User u : users) {
    // do something with it...

Alternatively, you can use an AggregateResult query which would query the child and group by the Id lookup.

// Assumes you have a Lookup called User__c
Map<Id, Integer> userAppCountMap = new Map<Id, Integer>();
for (AggregateResult aggRes : [
      SELECT COUNT(ID) numApps, User__c userId
      FROM Application__c
      GROUP BY User__c
]) {
    Id userId = (Id) aggRes.get('userId');
    Integer numApps = (Integer) aggRes.get('numApps');
    userAppCountMap.put(userId, numApps);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.