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
HareHare 

how to bulkify soql with multiple where conditions

i have 3 objects   Child__c is junction object , ParentA__c is master obj, Parentb__c master object.

so child__c (Many to Many relation ship) is junction object bitween ParentA__c and ParentB__c
in child__c i have 2 date fiels Startdate, enddate
while createing a junction object record need to maintain uniqness using ParentA__c ,ParentB__c and range of Startdate, enddate
example :  dd/mm/yyyy
    Record1: startdate  10/06/2016  enddate 10/07/2016  save record sucessfully          
     Record2: startdate  10/06/2016  enddate 02/07/2016  need to give error message 
      Record3: startdate  20/06/2016  enddate 20/07/2017  save record sucessfully
     Record4: startdate  20/06/2016  enddate 01/07/2016 need to give error message 

for this i wrote below sample code please help me bulkyfy

trigger Jundupcheck on Child__c (before insert) {
for (Child__c  ci : trigger.new) {


     
// We only care if there is one record<br>      
List<Child__c> resultList = [SELECT id,Name,Enddate__c,StartDate__c,(selected id)  FROM Child__c  WHERE  ParentA__c = :ci.ParentA__c AND   ParentB__c = :ci.ParentB__c and  ( (StartDate__c >= :ci.StartDate__c AND StartDate__c <= :ci.EndDate__c) OR (endDate__c  >= :ci.StartDate__c AND endDate__c  <= :ci.endDate__c) )  ];
                     
            // Raise the error back if any records found    
            
            if (resultList.size()>0) {
             ci.addError('Duplicate record, a Affisiation already exists for that combination');    
             }  }

}
KevinPKevinP
something like this should work:
List<Child__C> junctionObjs = new List<Child__C>();

List<Id> ParentAObjs = new List<Id>();
List<Id> ParentBObjs = new List<Id>();

for(Child__C c:trigger.new){
    parentAObjs.add(c.parentA__C);
    parentBObjs.add(c.parentB__c);
}

JunctionObjs = [
SELECT startDate__C, endDate__C
FROM Child__C
WHERE ParentA__C in :parentAObjs AND
    parentB__c in :parentBObjs
];

for(Child__c j :JunctionObjs) {
    for(Child__c c: Trigger.new) {
        if(c.parentA__c = j.parentA__c && c.parentB__c = j.parentB__c){
            if((c.startdate__c < j.startdate__c && c.endDate__c > j.endDate__c) || 
               (c.startdate__c > j.startdate__c && c.startdate__c < j.enddate__c && c.enddate__c > j.enddate__c) ||
               (c.startdate__c < j.startdate__c && c.endDate > j.startdate__c && c.enddate__c < j.enddate__c)
            ) {
                   c.addError('You're attempting to insert a record that overlaps time-wise with an existing child object');
              }
        }
    }
}