alias join tables
authorChuck Hagenbuch <chuck@horde.org>
Tue, 25 Aug 2009 03:45:26 +0000 (23:45 -0400)
committerChuck Hagenbuch <chuck@horde.org>
Tue, 25 Aug 2009 03:46:06 +0000 (23:46 -0400)
fixes a bug when doing self joins (for example, parent/child relationships among
the same kind of entity, like clotho_wbs_items).

framework/Rdo/lib/Horde/Rdo/Query.php

index be201a8..f6724c3 100644 (file)
@@ -38,19 +38,24 @@ class Horde_Rdo_Query
     public $relationships = array();
 
     /**
-     * @var array
+     * @var integer
      */
-    protected $_sortby = array();
+    public $limit;
 
     /**
      * @var integer
      */
-    public $limit;
+    public $limitOffset = null;
+
+    /**
+     * @var array
+     */
+    protected $_sortby = array();
 
     /**
      * @var integer
      */
-    public $limitOffset = null;
+    protected $_alias = 0;
 
     /**
      * Turn any of the acceptable query shorthands into a full
@@ -327,16 +332,18 @@ class Horde_Rdo_Query
     {
         foreach ($this->relationships as $relationship) {
             $relsql = array();
+            $table = $relationship['table'];
+            $tableAlias = $this->_alias($table);
             foreach ($relationship['query'] as $key => $value) {
                 if ($value instanceof Horde_Rdo_Query_Literal) {
-                    $relsql[] = $key . ' = ' . (string)$value;
+                    $relsql[] = $key . ' = ' . str_replace("{$table}.", "{$tableAlias}.", (string)$value);
                 } else {
                     $relsql[] = $key . ' = ?';
                     $bindParams[] = $value;
                 }
             }
 
-            $sql .= ' ' . $relationship['join_type'] . ' ' . $relationship['table'] . ' ON ' . implode(' AND ', $relsql);
+            $sql .= ' ' . $relationship['join_type'] . ' ' . $relationship['table'] . ' AS ' . $tableAlias . ' ON ' . implode(' AND ', $relsql);
         }
     }
 
@@ -416,6 +423,14 @@ class Horde_Rdo_Query
     }
 
     /**
+     * Get a unique table alias
+     */
+    protected function _alias($tableName)
+    {
+        return 't' . $this->_alias;
+    }
+
+    /**
      * Take a query array and replace @field@ placeholders with values
      * that will match in the load query.
      *