CRM-20594: Optimze Counting of Reltionships on Contact Summary
authorCamilo Rodriguez <camilo@compucorp.co.uk>
Wed, 17 May 2017 16:00:47 +0000 (16:00 +0000)
committerCamilo Rodriguez <camilo@compucorp.co.uk>
Wed, 17 May 2017 16:00:47 +0000 (16:00 +0000)
Contacts with a lot of relationships (over 5000) were taking a lot of time to
load.  This was because the count of relationships was being done by fetching
ALL records of relationships associated to the contact, and then counting the
number of elements in the resulting array.

Fixed by changing the call to CRM_Contact_BAO_Relationship::getRelationship()
being used in CRM_Contact_BAO_Contact::getCountComponent(), passing the
$count parameter as 1 instead of 0, so counting is done by the database by
building a 'SELECT COUNT(*)' type of query.

Also, removed some unnecessary joins when counting records in DB, ie. when
$count flag is 1.

CRM/Contact/BAO/Contact.php [changed mode: 0644->0755]
CRM/Contact/BAO/Relationship.php [changed mode: 0644->0755]

old mode 100644 (file)
new mode 100755 (executable)
index d547e2a..3e95bcd
@@ -2574,11 +2574,11 @@ AND       civicrm_openid.is_primary = 1";
       case 'rel':
         $result = CRM_Contact_BAO_Relationship::getRelationship($contactId,
           CRM_Contact_BAO_Relationship::CURRENT,
-          0, 0, 0,
+          0, 1, 0,
           NULL, NULL,
           TRUE
         );
-        return count($result);
+        return $result;
 
       case 'group':
 
old mode 100644 (file)
new mode 100755 (executable)
index aa4f472..d066665
@@ -1145,13 +1145,17 @@ INNER JOIN  civicrm_contact ";
     else {
       $from .= 'ON ( civicrm_contact.id = civicrm_relationship.contact_id_b ) ';
     }
-    $from .= "
+
+    if (!$count) {
+      $from .= "
 LEFT JOIN  civicrm_address ON (civicrm_address.contact_id = civicrm_contact.id AND civicrm_address.is_primary = 1)
 LEFT JOIN  civicrm_phone   ON (civicrm_phone.contact_id = civicrm_contact.id AND civicrm_phone.is_primary = 1)
 LEFT JOIN  civicrm_email   ON (civicrm_email.contact_id = civicrm_contact.id AND civicrm_email.is_primary = 1)
 LEFT JOIN  civicrm_state_province ON (civicrm_address.state_province_id = civicrm_state_province.id)
 LEFT JOIN  civicrm_country ON (civicrm_address.country_id = civicrm_country.id)
 ";
+    }
+
     $where = 'WHERE ( 1 )';
     if ($contactId) {
       if ($direction == 'a_b') {