From: Tim Otten Date: Wed, 21 May 2014 05:36:05 +0000 (-0700) Subject: CRM-14478 - CRM_Core_EntityReference - Move SQL construction X-Git-Url: https://vcs.fsf.org/?a=commitdiff_plain;h=de49f39c09959102256bcafd8e67cf317f8525e2;p=civicrm-core.git CRM-14478 - CRM_Core_EntityReference - Move SQL construction 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. --- diff --git a/CRM/Core/DAO.php b/CRM/Core/DAO.php index c2f18f7d3a..f786e089e8 100644 --- a/CRM/Core/DAO.php +++ b/CRM/Core/DAO.php @@ -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 = <<getReferenceTable()} -WHERE {$refColumn} = %1 -EOS; - if ($refSpec->isGeneric()) { - $params[2] = array(static::getTableName(), 'String'); - $sql .= <<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; diff --git a/CRM/Core/EntityReference.php b/CRM/Core/EntityReference.php index 3b5312833d..38b7890682 100644 --- a/CRM/Core/EntityReference.php +++ b/CRM/Core/EntityReference.php @@ -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 = <<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 .= <<getTypeColumn()} = %2 +EOS; + } + $daoName = CRM_Core_DAO_AllCoreTables::getClassForTable($this->getReferenceTable()); + $result = CRM_Core_DAO::executeQuery($sql, $params, TRUE, $daoName); + return $result; + } }