Merge pull request #19525 from eileenmcnaughton/member_soft
[civicrm-core.git] / CRM / Contact / BAO / Query.php
index c296260208a63db033e0a517d9cae1a830f30f9d..baa41722cd9e9275814e0a82fdffee7f07ce8d16 100644 (file)
@@ -1112,8 +1112,10 @@ class CRM_Contact_BAO_Query {
         }
 
         $field = $this->_fields[$elementName] ?? NULL;
-        if (isset($this->_pseudoConstantsSelect[$field['name']])) {
-          $this->_pseudoConstantsSelect[$name . '-' . $field['name']] = $this->_pseudoConstantsSelect[$field['name']];
+        if (!empty($field)) {
+          if (isset($this->_pseudoConstantsSelect[$field['name']])) {
+            $this->_pseudoConstantsSelect[$name . '-' . $field['name']] = $this->_pseudoConstantsSelect[$field['name']];
+          }
         }
 
         // hack for profile, add location id
@@ -5814,11 +5816,23 @@ AND   displayRelType.is_active = 1
       $this->_qill[0][] = $iqill;
     }
     if (strpos($from, $qcache['from']) === FALSE) {
-      // lets replace all the INNER JOIN's in the $from so we dont exclude other data
-      // this happens when we have an event_type in the quert (CRM-7969)
-      $from = str_replace("INNER JOIN", "LEFT JOIN", $from);
-      $from .= $qcache['from'];
+      if (strpos($from, "INNER JOIN") !== FALSE) {
+        // lets replace all the INNER JOIN's in the $from so we dont exclude other data
+        // this happens when we have an event_type in the quert (CRM-7969)
+        $from = str_replace("INNER JOIN", "LEFT JOIN", $from);
+        // Make sure the relationship join right after the FROM and other joins afterwards.
+        // This gives us the possibility to change the join on civicrm case.
+        $from = preg_replace("/LEFT JOIN/", $qcache['from'] . " LEFT JOIN", $from, 1);
+      }
+      else {
+        $from .= $qcache['from'];
+      }
       $where = $qcache['where'];
+      if (!empty($this->_tables['civicrm_case'])) {
+        // Change the join on CiviCRM case so that it joins on the right contac from the relationship.
+        $from = str_replace("ON civicrm_case_contact.contact_id = contact_a.id", "ON civicrm_case_contact.contact_id = transform_temp.contact_id", $from);
+        $where .= " AND displayRelType.case_id = civicrm_case_contact.case_id ";
+      }
       if (!empty($this->_permissionFromClause) && !stripos($from, 'aclContactCache')) {
         $from .= " $this->_permissionFromClause";
       }