CRM-14478 - CRM_Core_EntityReference - Move SQL construction
authorTim Otten <totten@civicrm.org>
Wed, 21 May 2014 05:36:05 +0000 (22:36 -0700)
committerTim Otten <totten@civicrm.org>
Fri, 23 May 2014 03:40:24 +0000 (20:40 -0700)
This anticipates polymorphic SQL construction -- where have different
classes for different types of references (eg conventional SQL FKs; dynamic
FK; option-value FKs) and where each class constructs slightly different
SQL.

CRM/Core/DAO.php
CRM/Core/EntityReference.php

index c2f18f7d3a8ed7b9ddaf7bf1a71ae9cc1299870b..f786e089e81faef6c63c2ab9c900de106c6d6294 100644 (file)
@@ -1741,22 +1741,9 @@ SELECT contact_id
 
     $occurrences = array();
     foreach ($links as $refSpec) {
-      $refColumn = $refSpec->getReferenceKey();
-      $targetColumn = $refSpec->getTargetKey();
-      $params = array(1 => array($this->$targetColumn, 'String'));
-      $sql = <<<EOS
-SELECT id
-FROM {$refSpec->getReferenceTable()}
-WHERE {$refColumn} = %1
-EOS;
-      if ($refSpec->isGeneric()) {
-        $params[2] = array(static::getTableName(), 'String');
-        $sql .= <<<EOS
-    AND {$refSpec->getTypeColumn()} = %2
-EOS;
-      }
+      /** @var $refSpec CRM_Core_EntityReference */
       $daoName = CRM_Core_DAO_AllCoreTables::getClassForTable($refSpec->getReferenceTable());
-      $result = self::executeQuery($sql, $params, TRUE, $daoName);
+      $result = $refSpec->findReferences($this);
       while ($result->fetch()) {
         $obj = new $daoName();
         $obj->id = $result->id;
index 3b5312833daf0ff78a0d3b5051c36976a1eff3d3..38b7890682294eb096940630daf8c2e83d50a93a 100644 (file)
@@ -46,4 +46,32 @@ class CRM_Core_EntityReference {
   function isGeneric() {
     return ($this->refTypeColumn !== NULL);
   }
+
+  /**
+   * Create a query to find references to a particular record
+   *
+   * @param CRM_Core_DAO $targetDao the instance for which we want references
+   * @return CRM_Core_DAO a query-handle (like the result of CRM_Core_DAO::executeQuery)
+   */
+  public function findReferences($targetDao) {
+    $refColumn = $this->getReferenceKey();
+    $targetColumn = $this->getTargetKey();
+    $params = array(1 => array($targetDao->$targetColumn, 'String'));
+    $sql = <<<EOS
+SELECT id
+FROM {$this->getReferenceTable()}
+WHERE {$refColumn} = %1
+EOS;
+    if ($this->isGeneric()) {
+      // If anyone complains about $dao::getTableName(), then could use
+      // "$daoClass=get_class($dao); $daoClass::getTableName();"
+      $params[2] = array($targetDao::getTableName(), 'String');
+      $sql .= <<<EOS
+    AND {$this->getTypeColumn()} = %2
+EOS;
+    }
+    $daoName = CRM_Core_DAO_AllCoreTables::getClassForTable($this->getReferenceTable());
+    $result = CRM_Core_DAO::executeQuery($sql, $params, TRUE, $daoName);
+    return $result;
+  }
 }