PageRenderTime 61ms CodeModel.GetById 2ms app.highlight 47ms RepoModel.GetById 1ms app.codeStats 1ms

/framework/db/ar/CActiveFinder.php

https://bitbucket.org/penkoh/yii
PHP | 1589 lines | 1178 code | 128 blank | 283 comment | 165 complexity | 748beb8d96349c622af1cfd490964f36 MD5 | raw file

Large files files are truncated, but you can click here to view the full file

   1<?php
   2/**
   3 * CActiveRecord class file.
   4 *
   5 * @author Qiang Xue <qiang.xue@gmail.com>
   6 * @link http://www.yiiframework.com/
   7 * @copyright Copyright &copy; 2008-2011 Yii Software LLC
   8 * @license http://www.yiiframework.com/license/
   9 */
  10
  11/**
  12 * CActiveFinder implements eager loading and lazy loading of related active records.
  13 *
  14 * When used in eager loading, this class provides the same set of find methods as
  15 * {@link CActiveRecord}.
  16 *
  17 * @author Qiang Xue <qiang.xue@gmail.com>
  18 * @package system.db.ar
  19 * @since 1.0
  20 */
  21class CActiveFinder extends CComponent
  22{
  23	/**
  24	 * @var boolean join all tables all at once. Defaults to false.
  25	 * This property is internally used.
  26	 */
  27	public $joinAll=false;
  28	/**
  29	 * @var boolean whether the base model has limit or offset.
  30	 * This property is internally used.
  31	 */
  32	public $baseLimited=false;
  33
  34	private $_joinCount=0;
  35	private $_joinTree;
  36	private $_builder;
  37
  38	/**
  39	 * Constructor.
  40	 * A join tree is built up based on the declared relationships between active record classes.
  41	 * @param CActiveRecord $model the model that initiates the active finding process
  42	 * @param mixed $with the relation names to be actively looked for
  43	 */
  44	public function __construct($model,$with)
  45	{
  46		$this->_builder=$model->getCommandBuilder();
  47		$this->_joinTree=new CJoinElement($this,$model);
  48		$this->buildJoinTree($this->_joinTree,$with);
  49	}
  50
  51	/**
  52	 * Do not call this method. This method is used internally to perform the relational query
  53	 * based on the given DB criteria.
  54	 * @param CDbCriteria $criteria the DB criteria
  55	 * @param boolean $all whether to bring back all records
  56	 * @return mixed the query result
  57	 */
  58	public function query($criteria,$all=false)
  59	{
  60		$this->joinAll=$criteria->together===true;
  61
  62		if($criteria->alias!='')
  63		{
  64			$this->_joinTree->tableAlias=$criteria->alias;
  65			$this->_joinTree->rawTableAlias=$this->_builder->getSchema()->quoteTableName($criteria->alias);
  66		}
  67
  68		$this->_joinTree->find($criteria);
  69		$this->_joinTree->afterFind();
  70
  71		if($all)
  72		{
  73			$result = array_values($this->_joinTree->records);
  74			if ($criteria->index!==null)
  75			{
  76				$index=$criteria->index;
  77				$array=array();
  78				foreach($result as $object)
  79					$array[$object->$index]=$object;
  80				$result=$array;
  81			}
  82		}
  83		elseif(count($this->_joinTree->records))
  84			$result = reset($this->_joinTree->records);
  85		else
  86			$result = null;
  87
  88		$this->destroyJoinTree();
  89		return $result;
  90	}
  91
  92	/**
  93	 * This method is internally called.
  94	 * @param string $sql the SQL statement
  95	 * @param array $params parameters to be bound to the SQL statement
  96	 * @return CActiveRecord
  97	 */
  98	public function findBySql($sql,$params=array())
  99	{
 100		Yii::trace(get_class($this->_joinTree->model).'.findBySql() eagerly','system.db.ar.CActiveRecord');
 101		if(($row=$this->_builder->createSqlCommand($sql,$params)->queryRow())!==false)
 102		{
 103			$baseRecord=$this->_joinTree->model->populateRecord($row,false);
 104			$this->_joinTree->findWithBase($baseRecord);
 105			$this->_joinTree->afterFind();
 106			$this->destroyJoinTree();
 107			return $baseRecord;
 108		}
 109		else
 110			$this->destroyJoinTree();
 111	}
 112
 113	/**
 114	 * This method is internally called.
 115	 * @param string $sql the SQL statement
 116	 * @param array $params parameters to be bound to the SQL statement
 117	 * @return CActiveRecord[]
 118	 */
 119	public function findAllBySql($sql,$params=array())
 120	{
 121		Yii::trace(get_class($this->_joinTree->model).'.findAllBySql() eagerly','system.db.ar.CActiveRecord');
 122		if(($rows=$this->_builder->createSqlCommand($sql,$params)->queryAll())!==array())
 123		{
 124			$baseRecords=$this->_joinTree->model->populateRecords($rows,false);
 125			$this->_joinTree->findWithBase($baseRecords);
 126			$this->_joinTree->afterFind();
 127			$this->destroyJoinTree();
 128			return $baseRecords;
 129		}
 130		else
 131		{
 132			$this->destroyJoinTree();
 133			return array();
 134		}
 135	}
 136
 137	/**
 138	 * This method is internally called.
 139	 * @param CDbCriteria $criteria the query criteria
 140	 * @return string
 141	 */
 142	public function count($criteria)
 143	{
 144		Yii::trace(get_class($this->_joinTree->model).'.count() eagerly','system.db.ar.CActiveRecord');
 145		$this->joinAll=$criteria->together!==true;
 146
 147		$alias=$criteria->alias===null ? 't' : $criteria->alias;
 148		$this->_joinTree->tableAlias=$alias;
 149		$this->_joinTree->rawTableAlias=$this->_builder->getSchema()->quoteTableName($alias);
 150
 151		$n=$this->_joinTree->count($criteria);
 152		$this->destroyJoinTree();
 153		return $n;
 154	}
 155
 156	/**
 157	 * Finds the related objects for the specified active record.
 158	 * This method is internally invoked by {@link CActiveRecord} to support lazy loading.
 159	 * @param CActiveRecord $baseRecord the base record whose related objects are to be loaded
 160	 */
 161	public function lazyFind($baseRecord)
 162	{
 163		$this->_joinTree->lazyFind($baseRecord);
 164		if(!empty($this->_joinTree->children))
 165		{
 166			foreach($this->_joinTree->children as $child)
 167				$child->afterFind();
 168		}
 169		$this->destroyJoinTree();
 170	}
 171
 172	private function destroyJoinTree()
 173	{
 174		if($this->_joinTree!==null)
 175			$this->_joinTree->destroy();
 176		$this->_joinTree=null;
 177	}
 178
 179	/**
 180	 * Builds up the join tree representing the relationships involved in this query.
 181	 * @param CJoinElement $parent the parent tree node
 182	 * @param mixed $with the names of the related objects relative to the parent tree node
 183	 * @param array $options additional query options to be merged with the relation
 184	 */
 185	private function buildJoinTree($parent,$with,$options=null)
 186	{
 187		if($parent instanceof CStatElement)
 188			throw new CDbException(Yii::t('yii','The STAT relation "{name}" cannot have child relations.',
 189				array('{name}'=>$parent->relation->name)));
 190
 191		if(is_string($with))
 192		{
 193			if(($pos=strrpos($with,'.'))!==false)
 194			{
 195				$parent=$this->buildJoinTree($parent,substr($with,0,$pos));
 196				$with=substr($with,$pos+1);
 197			}
 198
 199			// named scope
 200			$scopes=array();
 201			if(($pos=strpos($with,':'))!==false)
 202			{
 203				$scopes=explode(':',substr($with,$pos+1));
 204				$with=substr($with,0,$pos);
 205			}
 206
 207			if(isset($parent->children[$with]) && $parent->children[$with]->master===null)
 208				return $parent->children[$with];
 209
 210			if(($relation=$parent->model->getActiveRelation($with))===null)
 211				throw new CDbException(Yii::t('yii','Relation "{name}" is not defined in active record class "{class}".',
 212					array('{class}'=>get_class($parent->model), '{name}'=>$with)));
 213
 214			$relation=clone $relation;
 215			$model=CActiveRecord::model($relation->className);
 216
 217			if($relation instanceof CActiveRelation)
 218			{
 219				$oldAlias=$model->getTableAlias(false,false);
 220				if(isset($options['alias']))
 221					$model->setTableAlias($options['alias']);
 222				elseif($relation->alias===null)
 223					$model->setTableAlias($relation->name);
 224				else
 225					$model->setTableAlias($relation->alias);
 226			}
 227
 228			if(!empty($relation->scopes))
 229				$scopes=array_merge($scopes,(array)$relation->scopes); // no need for complex merging
 230
 231			if(!empty($options['scopes']))
 232				$scopes=array_merge($scopes,(array)$options['scopes']); // no need for complex merging
 233
 234			$model->resetScope(false);
 235			$criteria=$model->getDbCriteria();
 236			$criteria->scopes=$scopes;
 237			$model->beforeFindInternal();
 238			$model->applyScopes($criteria);
 239			$relation->mergeWith($criteria,true);
 240
 241			// dynamic options
 242			if($options!==null)
 243				$relation->mergeWith($options);
 244
 245			if($relation instanceof CActiveRelation)
 246				$model->setTableAlias($oldAlias);
 247
 248			if($relation instanceof CStatRelation)
 249				return new CStatElement($this,$relation,$parent);
 250			else
 251			{
 252				if(isset($parent->children[$with]))
 253				{
 254					$element=$parent->children[$with];
 255					$element->relation=$relation;
 256				}
 257				else
 258					$element=new CJoinElement($this,$relation,$parent,++$this->_joinCount);
 259				if(!empty($relation->through))
 260				{
 261					$slave=$this->buildJoinTree($parent,$relation->through,array('select'=>false));
 262					$slave->master=$element;
 263					$element->slave=$slave;
 264				}
 265				$parent->children[$with]=$element;
 266				if(!empty($relation->with))
 267					$this->buildJoinTree($element,$relation->with);
 268				return $element;
 269			}
 270		}
 271
 272		// $with is an array, keys are relation name, values are relation spec
 273		foreach($with as $key=>$value)
 274		{
 275			if(is_string($value))  // the value is a relation name
 276				$this->buildJoinTree($parent,$value);
 277			elseif(is_string($key) && is_array($value))
 278				$this->buildJoinTree($parent,$key,$value);
 279		}
 280	}
 281}
 282
 283
 284/**
 285 * CJoinElement represents a tree node in the join tree created by {@link CActiveFinder}.
 286 *
 287 * @author Qiang Xue <qiang.xue@gmail.com>
 288 * @package system.db.ar
 289 * @since 1.0
 290 */
 291class CJoinElement
 292{
 293	/**
 294	 * @var integer the unique ID of this tree node
 295	 */
 296	public $id;
 297	/**
 298	 * @var CActiveRelation the relation represented by this tree node
 299	 */
 300	public $relation;
 301	/**
 302	 * @var CActiveRelation the master relation
 303	 */
 304	public $master;
 305	/**
 306	 * @var CActiveRelation the slave relation
 307	 */
 308	public $slave;
 309	/**
 310	 * @var CActiveRecord the model associated with this tree node
 311	 */
 312	public $model;
 313	/**
 314	 * @var array list of active records found by the queries. They are indexed by primary key values.
 315	 */
 316	public $records=array();
 317	/**
 318	 * @var array list of child join elements
 319	 */
 320	public $children=array();
 321	/**
 322	 * @var array list of stat elements
 323	 */
 324	public $stats=array();
 325	/**
 326	 * @var string table alias for this join element
 327	 */
 328	public $tableAlias;
 329	/**
 330	 * @var string the quoted table alias for this element
 331	 */
 332	public $rawTableAlias;
 333
 334	private $_finder;
 335	private $_builder;
 336	private $_parent;
 337	private $_pkAlias;  				// string or name=>alias
 338	private $_columnAliases=array();	// name=>alias
 339	private $_joined=false;
 340	private $_table;
 341	private $_related=array();			// PK, relation name, related PK => true
 342
 343	/**
 344	 * Constructor.
 345	 * @param CActiveFinder $finder the finder
 346	 * @param mixed $relation the relation (if the third parameter is not null)
 347	 * or the model (if the third parameter is null) associated with this tree node.
 348	 * @param CJoinElement $parent the parent tree node
 349	 * @param integer $id the ID of this tree node that is unique among all the tree nodes
 350	 */
 351	public function __construct($finder,$relation,$parent=null,$id=0)
 352	{
 353		$this->_finder=$finder;
 354		$this->id=$id;
 355		if($parent!==null)
 356		{
 357			$this->relation=$relation;
 358			$this->_parent=$parent;
 359			$this->model=CActiveRecord::model($relation->className);
 360			$this->_builder=$this->model->getCommandBuilder();
 361			$this->tableAlias=$relation->alias===null?$relation->name:$relation->alias;
 362			$this->rawTableAlias=$this->_builder->getSchema()->quoteTableName($this->tableAlias);
 363			$this->_table=$this->model->getTableSchema();
 364		}
 365		else  // root element, the first parameter is the model.
 366		{
 367			$this->model=$relation;
 368			$this->_builder=$relation->getCommandBuilder();
 369			$this->_table=$relation->getTableSchema();
 370			$this->tableAlias=$this->model->getTableAlias();
 371			$this->rawTableAlias=$this->_builder->getSchema()->quoteTableName($this->tableAlias);
 372		}
 373
 374		// set up column aliases, such as t1_c2
 375		$table=$this->_table;
 376		if($this->model->getDbConnection()->getDriverName()==='oci')  // Issue 482
 377			$prefix='T'.$id.'_C';
 378		else
 379			$prefix='t'.$id.'_c';
 380		foreach($table->getColumnNames() as $key=>$name)
 381		{
 382			$alias=$prefix.$key;
 383			$this->_columnAliases[$name]=$alias;
 384			if($table->primaryKey===$name)
 385				$this->_pkAlias=$alias;
 386			elseif(is_array($table->primaryKey) && in_array($name,$table->primaryKey))
 387				$this->_pkAlias[$name]=$alias;
 388		}
 389	}
 390
 391	/**
 392	 * Removes references to child elements and finder to avoid circular references.
 393	 * This is internally used.
 394	 */
 395	public function destroy()
 396	{
 397		if(!empty($this->children))
 398		{
 399			foreach($this->children as $child)
 400				$child->destroy();
 401		}
 402		unset($this->_finder, $this->_parent, $this->model, $this->relation, $this->master, $this->slave, $this->records, $this->children, $this->stats);
 403	}
 404
 405	/**
 406	 * Performs the recursive finding with the criteria.
 407	 * @param CDbCriteria $criteria the query criteria
 408	 */
 409	public function find($criteria=null)
 410	{
 411		if($this->_parent===null) // root element
 412		{
 413			$query=new CJoinQuery($this,$criteria);
 414			$this->_finder->baseLimited=($criteria->offset>=0 || $criteria->limit>=0);
 415			$this->buildQuery($query);
 416			$this->_finder->baseLimited=false;
 417			$this->runQuery($query);
 418		}
 419		elseif(!$this->_joined && !empty($this->_parent->records)) // not joined before
 420		{
 421			$query=new CJoinQuery($this->_parent);
 422			$this->_joined=true;
 423			$query->join($this);
 424			$this->buildQuery($query);
 425			$this->_parent->runQuery($query);
 426		}
 427
 428		foreach($this->children as $child) // find recursively
 429			$child->find();
 430
 431		foreach($this->stats as $stat)
 432			$stat->query();
 433	}
 434
 435	/**
 436	 * Performs lazy find with the specified base record.
 437	 * @param CActiveRecord $baseRecord the active record whose related object is to be fetched.
 438	 */
 439	public function lazyFind($baseRecord)
 440	{
 441		if(is_string($this->_table->primaryKey))
 442			$this->records[$baseRecord->{$this->_table->primaryKey}]=$baseRecord;
 443		else
 444		{
 445			$pk=array();
 446			foreach($this->_table->primaryKey as $name)
 447				$pk[$name]=$baseRecord->$name;
 448			$this->records[serialize($pk)]=$baseRecord;
 449		}
 450
 451		foreach($this->stats as $stat)
 452			$stat->query();
 453
 454		switch(count($this->children))
 455		{
 456			case 0:
 457				return;
 458			break;
 459			case 1:
 460				$child=reset($this->children);
 461			break;
 462			default: // bridge(s) inside
 463				$child=end($this->children);
 464			break;
 465		}
 466
 467		$query=new CJoinQuery($child);
 468		$query->selects=array();
 469		$query->selects[]=$child->getColumnSelect($child->relation->select);
 470		$query->conditions=array();
 471		$query->conditions[]=$child->relation->condition;
 472		$query->conditions[]=$child->relation->on;
 473		$query->groups[]=$child->relation->group;
 474		$query->joins[]=$child->relation->join;
 475		$query->havings[]=$child->relation->having;
 476		$query->orders[]=$child->relation->order;
 477		if(is_array($child->relation->params))
 478			$query->params=$child->relation->params;
 479		$query->elements[$child->id]=true;
 480		if($child->relation instanceof CHasManyRelation)
 481		{
 482			$query->limit=$child->relation->limit;
 483			$query->offset=$child->relation->offset;
 484		}
 485
 486		$child->applyLazyCondition($query,$baseRecord);
 487
 488		$this->_joined=true;
 489		$child->_joined=true;
 490
 491		$this->_finder->baseLimited=false;
 492		$child->buildQuery($query);
 493		$child->runQuery($query);
 494		foreach($child->children as $c)
 495			$c->find();
 496
 497		if(empty($child->records))
 498			return;
 499		if($child->relation instanceof CHasOneRelation || $child->relation instanceof CBelongsToRelation)
 500			$baseRecord->addRelatedRecord($child->relation->name,reset($child->records),false);
 501		else // has_many and many_many
 502		{
 503			foreach($child->records as $record)
 504			{
 505				if($child->relation->index!==null)
 506					$index=$record->{$child->relation->index};
 507				else
 508					$index=true;
 509				$baseRecord->addRelatedRecord($child->relation->name,$record,$index);
 510			}
 511		}
 512	}
 513
 514	/**
 515	 * Apply Lazy Condition
 516	 * @param CJoinQuery $query represents a JOIN SQL statements
 517	 * @param CActiveRecord $record the active record whose related object is to be fetched.
 518	 */
 519	private function applyLazyCondition($query,$record)
 520	{
 521		$schema=$this->_builder->getSchema();
 522		$parent=$this->_parent;
 523		if($this->relation instanceof CManyManyRelation)
 524		{
 525			$joinTableName=$this->relation->getJunctionTableName();
 526			if(($joinTable=$schema->getTable($joinTableName))===null)
 527				throw new CDbException(Yii::t('yii','The relation "{relation}" in active record class "{class}" is not specified correctly: the join table "{joinTable}" given in the foreign key cannot be found in the database.',
 528					array('{class}'=>get_class($parent->model), '{relation}'=>$this->relation->name, '{joinTable}'=>$joinTableName)));
 529			$fks=$this->relation->getJunctionForeignKeys();
 530
 531			$joinAlias=$schema->quoteTableName($this->relation->name.'_'.$this->tableAlias);
 532			$parentCondition=array();
 533			$childCondition=array();
 534			$count=0;
 535			$params=array();
 536
 537			$fkDefined=true;
 538			foreach($fks as $i=>$fk)
 539			{
 540				if(isset($joinTable->foreignKeys[$fk]))  // FK defined
 541				{
 542					list($tableName,$pk)=$joinTable->foreignKeys[$fk];
 543					if(!isset($parentCondition[$pk]) && $schema->compareTableNames($parent->_table->rawName,$tableName))
 544					{
 545						$parentCondition[$pk]=$joinAlias.'.'.$schema->quoteColumnName($fk).'=:ypl'.$count;
 546						$params[':ypl'.$count]=$record->$pk;
 547						$count++;
 548					}
 549					elseif(!isset($childCondition[$pk]) && $schema->compareTableNames($this->_table->rawName,$tableName))
 550						$childCondition[$pk]=$this->getColumnPrefix().$schema->quoteColumnName($pk).'='.$joinAlias.'.'.$schema->quoteColumnName($fk);
 551					else
 552					{
 553						$fkDefined=false;
 554						break;
 555					}
 556				}
 557				else
 558				{
 559					$fkDefined=false;
 560					break;
 561				}
 562			}
 563
 564			if(!$fkDefined)
 565			{
 566				$parentCondition=array();
 567				$childCondition=array();
 568				$count=0;
 569				$params=array();
 570				foreach($fks as $i=>$fk)
 571				{
 572					if($i<count($parent->_table->primaryKey))
 573					{
 574						$pk=is_array($parent->_table->primaryKey) ? $parent->_table->primaryKey[$i] : $parent->_table->primaryKey;
 575						$parentCondition[$pk]=$joinAlias.'.'.$schema->quoteColumnName($fk).'=:ypl'.$count;
 576						$params[':ypl'.$count]=$record->$pk;
 577						$count++;
 578					}
 579					else
 580					{
 581						$j=$i-count($parent->_table->primaryKey);
 582						$pk=is_array($this->_table->primaryKey) ? $this->_table->primaryKey[$j] : $this->_table->primaryKey;
 583						$childCondition[$pk]=$this->getColumnPrefix().$schema->quoteColumnName($pk).'='.$joinAlias.'.'.$schema->quoteColumnName($fk);
 584					}
 585				}
 586			}
 587
 588			if($parentCondition!==array() && $childCondition!==array())
 589			{
 590				$join='INNER JOIN '.$joinTable->rawName.' '.$joinAlias.' ON ';
 591				$join.='('.implode(') AND (',$parentCondition).') AND ('.implode(') AND (',$childCondition).')';
 592				if(!empty($this->relation->on))
 593					$join.=' AND ('.$this->relation->on.')';
 594				$query->joins[]=$join;
 595				foreach($params as $name=>$value)
 596					$query->params[$name]=$value;
 597			}
 598			else
 599				throw new CDbException(Yii::t('yii','The relation "{relation}" in active record class "{class}" is specified with an incomplete foreign key. The foreign key must consist of columns referencing both joining tables.',
 600					array('{class}'=>get_class($parent->model), '{relation}'=>$this->relation->name)));
 601		}
 602		else
 603		{
 604			$element=$this;
 605			while($element->slave!==null)
 606			{
 607				$query->joins[]=$element->slave->joinOneMany($element->slave,$element->relation->foreignKey,$element,$parent);
 608				$element=$element->slave;
 609			}
 610			$fks=is_array($element->relation->foreignKey) ? $element->relation->foreignKey : preg_split('/\s*,\s*/',$element->relation->foreignKey,-1,PREG_SPLIT_NO_EMPTY);
 611			$prefix=$element->getColumnPrefix();
 612			$params=array();
 613			foreach($fks as $i=>$fk)
 614			{
 615				if(!is_int($i))
 616				{
 617					$pk=$fk;
 618					$fk=$i;
 619				}
 620
 621				if($this->relation instanceof CBelongsToRelation)
 622				{
 623					if(is_int($i))
 624					{
 625						if(isset($parent->_table->foreignKeys[$fk]))  // FK defined
 626							$pk=$parent->_table->foreignKeys[$fk][1];
 627						elseif(is_array($this->_table->primaryKey)) // composite PK
 628							$pk=$this->_table->primaryKey[$i];
 629						else
 630							$pk=$this->_table->primaryKey;
 631					}
 632					$params[$pk]=$record->$fk;
 633				}
 634				else
 635				{
 636					if(is_int($i))
 637					{
 638						if(isset($this->_table->foreignKeys[$fk]))  // FK defined
 639							$pk=$this->_table->foreignKeys[$fk][1];
 640						elseif(is_array($parent->_table->primaryKey)) // composite PK
 641							$pk=$parent->_table->primaryKey[$i];
 642						else
 643							$pk=$parent->_table->primaryKey;
 644					}
 645					$params[$fk]=$record->$pk;
 646				}
 647			}
 648			$count=0;
 649			foreach($params as $name=>$value)
 650			{
 651				$query->conditions[]=$prefix.$schema->quoteColumnName($name).'=:ypl'.$count;
 652				$query->params[':ypl'.$count]=$value;
 653				$count++;
 654			}
 655		}
 656	}
 657
 658	/**
 659	 * Performs the eager loading with the base records ready.
 660	 * @param mixed $baseRecords the available base record(s).
 661	 */
 662	public function findWithBase($baseRecords)
 663	{
 664		if(!is_array($baseRecords))
 665			$baseRecords=array($baseRecords);
 666		if(is_string($this->_table->primaryKey))
 667		{
 668			foreach($baseRecords as $baseRecord)
 669				$this->records[$baseRecord->{$this->_table->primaryKey}]=$baseRecord;
 670		}
 671		else
 672		{
 673			foreach($baseRecords as $baseRecord)
 674			{
 675				$pk=array();
 676				foreach($this->_table->primaryKey as $name)
 677					$pk[$name]=$baseRecord->$name;
 678				$this->records[serialize($pk)]=$baseRecord;
 679			}
 680		}
 681
 682		$query=new CJoinQuery($this);
 683		$this->buildQuery($query);
 684		if(count($query->joins)>1)
 685			$this->runQuery($query);
 686		foreach($this->children as $child)
 687			$child->find();
 688
 689		foreach($this->stats as $stat)
 690			$stat->query();
 691	}
 692
 693	/**
 694	 * Count the number of primary records returned by the join statement.
 695	 * @param CDbCriteria $criteria the query criteria
 696	 * @return string number of primary records. Note: type is string to keep max. precision.
 697	 */
 698	public function count($criteria=null)
 699	{
 700		$query=new CJoinQuery($this,$criteria);
 701		// ensure only one big join statement is used
 702		$this->_finder->baseLimited=false;
 703		$this->_finder->joinAll=true;
 704		$this->buildQuery($query);
 705
 706		$select=is_array($criteria->select) ? implode(',',$criteria->select) : $criteria->select;
 707		if($select!=='*' && !strncasecmp($select,'count',5))
 708			$query->selects=array($select);
 709		elseif(is_string($this->_table->primaryKey))
 710		{
 711			$prefix=$this->getColumnPrefix();
 712			$schema=$this->_builder->getSchema();
 713			$column=$prefix.$schema->quoteColumnName($this->_table->primaryKey);
 714			$query->selects=array("COUNT(DISTINCT $column)");
 715		}
 716		else
 717			$query->selects=array("COUNT(*)");
 718
 719		$query->orders=$query->groups=$query->havings=array();
 720		$query->limit=$query->offset=-1;
 721		$command=$query->createCommand($this->_builder);
 722		return $command->queryScalar();
 723	}
 724
 725	/**
 726	 * Calls {@link CActiveRecord::afterFind} of all the records.
 727	 */
 728	public function afterFind()
 729	{
 730		foreach($this->records as $record)
 731			$record->afterFindInternal();
 732		foreach($this->children as $child)
 733			$child->afterFind();
 734
 735		$this->children = null;
 736	}
 737
 738	/**
 739	 * Builds the join query with all descendant HAS_ONE and BELONGS_TO nodes.
 740	 * @param CJoinQuery $query the query being built up
 741	 */
 742	public function buildQuery($query)
 743	{
 744		foreach($this->children as $child)
 745		{
 746			if($child->master!==null)
 747				$child->_joined=true;
 748			elseif($child->relation instanceof CHasOneRelation || $child->relation instanceof CBelongsToRelation
 749				|| $this->_finder->joinAll || $child->relation->together || (!$this->_finder->baseLimited && $child->relation->together===null))
 750			{
 751				$child->_joined=true;
 752				$query->join($child);
 753				$child->buildQuery($query);
 754			}
 755		}
 756	}
 757
 758	/**
 759	 * Executes the join query and populates the query results.
 760	 * @param CJoinQuery $query the query to be executed.
 761	 */
 762	public function runQuery($query)
 763	{
 764		$command=$query->createCommand($this->_builder);
 765		foreach($command->queryAll() as $row)
 766			$this->populateRecord($query,$row);
 767	}
 768
 769	/**
 770	 * Populates the active records with the query data.
 771	 * @param CJoinQuery $query the query executed
 772	 * @param array $row a row of data
 773	 * @return CActiveRecord the populated record
 774	 */
 775	private function populateRecord($query,$row)
 776	{
 777		// determine the primary key value
 778		if(is_string($this->_pkAlias))  // single key
 779		{
 780			if(isset($row[$this->_pkAlias]))
 781				$pk=$row[$this->_pkAlias];
 782			else	// no matching related objects
 783				return null;
 784		}
 785		else // is_array, composite key
 786		{
 787			$pk=array();
 788			foreach($this->_pkAlias as $name=>$alias)
 789			{
 790				if(isset($row[$alias]))
 791					$pk[$name]=$row[$alias];
 792				else	// no matching related objects
 793					return null;
 794			}
 795			$pk=serialize($pk);
 796		}
 797
 798		// retrieve or populate the record according to the primary key value
 799		if(isset($this->records[$pk]))
 800			$record=$this->records[$pk];
 801		else
 802		{
 803			$attributes=array();
 804			$aliases=array_flip($this->_columnAliases);
 805			foreach($row as $alias=>$value)
 806			{
 807				if(isset($aliases[$alias]))
 808					$attributes[$aliases[$alias]]=$value;
 809			}
 810			$record=$this->model->populateRecord($attributes,false);
 811			foreach($this->children as $child)
 812			{
 813				if(!empty($child->relation->select))
 814					$record->addRelatedRecord($child->relation->name,null,$child->relation instanceof CHasManyRelation);
 815			}
 816			$this->records[$pk]=$record;
 817		}
 818
 819		// populate child records recursively
 820		foreach($this->children as $child)
 821		{
 822			if(!isset($query->elements[$child->id]) || empty($child->relation->select))
 823				continue;
 824			$childRecord=$child->populateRecord($query,$row);
 825			if($child->relation instanceof CHasOneRelation || $child->relation instanceof CBelongsToRelation)
 826				$record->addRelatedRecord($child->relation->name,$childRecord,false);
 827			else // has_many and many_many
 828			{
 829				// need to double check to avoid adding duplicated related objects
 830				if($childRecord instanceof CActiveRecord)
 831					$fpk=serialize($childRecord->getPrimaryKey());
 832				else
 833					$fpk=0;
 834				if(!isset($this->_related[$pk][$child->relation->name][$fpk]))
 835				{
 836					if($childRecord instanceof CActiveRecord && $child->relation->index!==null)
 837						$index=$childRecord->{$child->relation->index};
 838					else
 839						$index=true;
 840					$record->addRelatedRecord($child->relation->name,$childRecord,$index);
 841					$this->_related[$pk][$child->relation->name][$fpk]=true;
 842				}
 843			}
 844		}
 845
 846		return $record;
 847	}
 848
 849	/**
 850	 * @return string the table name and the table alias (if any). This can be used directly in SQL query without escaping.
 851	 */
 852	public function getTableNameWithAlias()
 853	{
 854		if($this->tableAlias!==null)
 855			return $this->_table->rawName . ' ' . $this->rawTableAlias;
 856		else
 857			return $this->_table->rawName;
 858	}
 859
 860	/**
 861	 * Generates the list of columns to be selected.
 862	 * Columns will be properly aliased and primary keys will be added to selection if they are not specified.
 863	 * @param mixed $select columns to be selected. Defaults to '*', indicating all columns.
 864	 * @return string the column selection
 865	 */
 866	public function getColumnSelect($select='*')
 867	{
 868		$schema=$this->_builder->getSchema();
 869		$prefix=$this->getColumnPrefix();
 870		$columns=array();
 871		if($select==='*')
 872		{
 873			foreach($this->_table->getColumnNames() as $name)
 874				$columns[]=$prefix.$schema->quoteColumnName($name).' AS '.$schema->quoteColumnName($this->_columnAliases[$name]);
 875		}
 876		else
 877		{
 878			if(is_string($select))
 879				$select=explode(',',$select);
 880			$selected=array();
 881			foreach($select as $name)
 882			{
 883				$name=trim($name);
 884				$matches=array();
 885				if(($pos=strrpos($name,'.'))!==false)
 886					$key=substr($name,$pos+1);
 887				else
 888					$key=$name;
 889				$key=trim($key,'\'"`');
 890
 891				if($key==='*')
 892				{
 893					foreach($this->_table->columns as $name=>$column)
 894					{
 895						$alias=$this->_columnAliases[$name];
 896						if(!isset($selected[$alias]))
 897						{
 898							$columns[]=$prefix.$column->rawName.' AS '.$schema->quoteColumnName($alias);
 899							$selected[$alias]=1;
 900						}
 901					}
 902					continue;
 903				}
 904
 905				if(isset($this->_columnAliases[$key]))  // simple column names
 906				{
 907					$columns[]=$prefix.$schema->quoteColumnName($key).' AS '.$schema->quoteColumnName($this->_columnAliases[$key]);
 908					$selected[$this->_columnAliases[$key]]=1;
 909				}
 910				elseif(preg_match('/^(.*?)\s+AS\s+(\w+)$/im',$name,$matches)) // if the column is already aliased
 911				{
 912					$alias=$matches[2];
 913					if(!isset($this->_columnAliases[$alias]) || $this->_columnAliases[$alias]!==$alias)
 914					{
 915						$this->_columnAliases[$alias]=$alias;
 916						$columns[]=$name;
 917						$selected[$alias]=1;
 918					}
 919				}
 920				else
 921					throw new CDbException(Yii::t('yii','Active record "{class}" is trying to select an invalid column "{column}". Note, the column must exist in the table or be an expression with alias.',
 922						array('{class}'=>get_class($this->model), '{column}'=>$name)));
 923			}
 924			// add primary key selection if they are not selected
 925			if(is_string($this->_pkAlias) && !isset($selected[$this->_pkAlias]))
 926				$columns[]=$prefix.$schema->quoteColumnName($this->_table->primaryKey).' AS '.$schema->quoteColumnName($this->_pkAlias);
 927			elseif(is_array($this->_pkAlias))
 928			{
 929				foreach($this->_table->primaryKey as $name)
 930					if(!isset($selected[$name]))
 931						$columns[]=$prefix.$schema->quoteColumnName($name).' AS '.$schema->quoteColumnName($this->_pkAlias[$name]);
 932			}
 933		}
 934
 935		return implode(', ',$columns);
 936	}
 937
 938	/**
 939	 * @return string the primary key selection
 940	 */
 941	public function getPrimaryKeySelect()
 942	{
 943		$schema=$this->_builder->getSchema();
 944		$prefix=$this->getColumnPrefix();
 945		$columns=array();
 946		if(is_string($this->_pkAlias))
 947			$columns[]=$prefix.$schema->quoteColumnName($this->_table->primaryKey).' AS '.$schema->quoteColumnName($this->_pkAlias);
 948		elseif(is_array($this->_pkAlias))
 949		{
 950			foreach($this->_pkAlias as $name=>$alias)
 951				$columns[]=$prefix.$schema->quoteColumnName($name).' AS '.$schema->quoteColumnName($alias);
 952		}
 953		return implode(', ',$columns);
 954	}
 955
 956	/**
 957	 * @return string the condition that specifies only the rows with the selected primary key values.
 958	 */
 959	public function getPrimaryKeyRange()
 960	{
 961		if(empty($this->records))
 962			return '';
 963		$values=array_keys($this->records);
 964		if(is_array($this->_table->primaryKey))
 965		{
 966			foreach($values as &$value)
 967				$value=unserialize($value);
 968		}
 969		return $this->_builder->createInCondition($this->_table,$this->_table->primaryKey,$values,$this->getColumnPrefix());
 970	}
 971
 972	/**
 973	 * @return string the column prefix for column reference disambiguation
 974	 */
 975	public function getColumnPrefix()
 976	{
 977		if($this->tableAlias!==null)
 978			return $this->rawTableAlias.'.';
 979		else
 980			return $this->_table->rawName.'.';
 981	}
 982
 983	/**
 984	 * @return string the join statement (this node joins with its parent)
 985	 */
 986	public function getJoinCondition()
 987	{
 988		$parent=$this->_parent;
 989		if($this->relation instanceof CManyManyRelation)
 990		{
 991			$schema=$this->_builder->getSchema();
 992			$joinTableName=$this->relation->getJunctionTableName();
 993			if(($joinTable=$schema->getTable($joinTableName))===null)
 994				throw new CDbException(Yii::t('yii','The relation "{relation}" in active record class "{class}" is not specified correctly: the join table "{joinTable}" given in the foreign key cannot be found in the database.',
 995					array('{class}'=>get_class($parent->model), '{relation}'=>$this->relation->name, '{joinTable}'=>$joinTableName)));
 996			$fks=$this->relation->getJunctionForeignKeys();
 997
 998			return $this->joinManyMany($joinTable,$fks,$parent);
 999		}
1000		else
1001		{
1002			$fks=is_array($this->relation->foreignKey) ? $this->relation->foreignKey : preg_split('/\s*,\s*/',$this->relation->foreignKey,-1,PREG_SPLIT_NO_EMPTY);
1003			if($this->relation instanceof CBelongsToRelation)
1004			{
1005				$pke=$this;
1006				$fke=$parent;
1007			}
1008			elseif($this->slave===null)
1009			{
1010				$pke=$parent;
1011				$fke=$this;
1012			}
1013			else
1014			{
1015				$pke=$this;
1016				$fke=$this->slave;
1017			}
1018			return $this->joinOneMany($fke,$fks,$pke,$parent);
1019		}
1020	}
1021
1022	/**
1023	 * Generates the join statement for one-many relationship.
1024	 * This works for HAS_ONE, HAS_MANY and BELONGS_TO.
1025	 * @param CJoinElement $fke the join element containing foreign keys
1026	 * @param array $fks the foreign keys
1027	 * @param CJoinElement $pke the join element containg primary keys
1028	 * @param CJoinElement $parent the parent join element
1029	 * @return string the join statement
1030	 * @throws CDbException if a foreign key is invalid
1031	 */
1032	private function joinOneMany($fke,$fks,$pke,$parent)
1033	{
1034		$schema=$this->_builder->getSchema();
1035		$joins=array();
1036		if(is_string($fks))
1037			$fks=preg_split('/\s*,\s*/',$fks,-1,PREG_SPLIT_NO_EMPTY);
1038		foreach($fks as $i=>$fk)
1039		{
1040			if(!is_int($i))
1041			{
1042				$pk=$fk;
1043				$fk=$i;
1044			}
1045
1046			if(!isset($fke->_table->columns[$fk]))
1047				throw new CDbException(Yii::t('yii','The relation "{relation}" in active record class "{class}" is specified with an invalid foreign key "{key}". There is no such column in the table "{table}".',
1048					array('{class}'=>get_class($parent->model), '{relation}'=>$this->relation->name, '{key}'=>$fk, '{table}'=>$fke->_table->name)));
1049
1050			if(is_int($i))
1051			{
1052				if(isset($fke->_table->foreignKeys[$fk]) && $schema->compareTableNames($pke->_table->rawName, $fke->_table->foreignKeys[$fk][0]))
1053					$pk=$fke->_table->foreignKeys[$fk][1];
1054				else // FK constraints undefined
1055				{
1056					if(is_array($pke->_table->primaryKey)) // composite PK
1057						$pk=$pke->_table->primaryKey[$i];
1058					else
1059						$pk=$pke->_table->primaryKey;
1060				}
1061			}
1062
1063			$joins[]=$fke->getColumnPrefix().$schema->quoteColumnName($fk) . '=' . $pke->getColumnPrefix().$schema->quoteColumnName($pk);
1064		}
1065		if(!empty($this->relation->on))
1066			$joins[]=$this->relation->on;
1067		return $this->relation->joinType . ' ' . $this->getTableNameWithAlias() . ' ON (' . implode(') AND (',$joins).')';
1068	}
1069
1070	/**
1071	 * Generates the join statement for many-many relationship.
1072	 * @param CDbTableSchema $joinTable the join table
1073	 * @param array $fks the foreign keys
1074	 * @param CJoinElement $parent the parent join element
1075	 * @return string the join statement
1076	 * @throws CDbException if a foreign key is invalid
1077	 */
1078	private function joinManyMany($joinTable,$fks,$parent)
1079	{
1080		$schema=$this->_builder->getSchema();
1081		$joinAlias=$schema->quoteTableName($this->relation->name.'_'.$this->tableAlias);
1082		$parentCondition=array();
1083		$childCondition=array();
1084
1085		$fkDefined=true;
1086		foreach($fks as $i=>$fk)
1087		{
1088			if(!isset($joinTable->columns[$fk]))
1089				throw new CDbException(Yii::t('yii','The relation "{relation}" in active record class "{class}" is specified with an invalid foreign key "{key}". There is no such column in the table "{table}".',
1090					array('{class}'=>get_class($parent->model), '{relation}'=>$this->relation->name, '{key}'=>$fk, '{table}'=>$joinTable->name)));
1091
1092			if(isset($joinTable->foreignKeys[$fk]))
1093			{
1094				list($tableName,$pk)=$joinTable->foreignKeys[$fk];
1095				if(!isset($parentCondition[$pk]) && $schema->compareTableNames($parent->_table->rawName,$tableName))
1096					$parentCondition[$pk]=$parent->getColumnPrefix().$schema->quoteColumnName($pk).'='.$joinAlias.'.'.$schema->quoteColumnName($fk);
1097				elseif(!isset($childCondition[$pk]) && $schema->compareTableNames($this->_table->rawName,$tableName))
1098					$childCondition[$pk]=$this->getColumnPrefix().$schema->quoteColumnName($pk).'='.$joinAlias.'.'.$schema->quoteColumnName($fk);
1099				else
1100				{
1101					$fkDefined=false;
1102					break;
1103				}
1104			}
1105			else
1106			{
1107				$fkDefined=false;
1108				break;
1109			}
1110		}
1111
1112		if(!$fkDefined)
1113		{
1114			$parentCondition=array();
1115			$childCondition=array();
1116			foreach($fks as $i=>$fk)
1117			{
1118				if($i<count($parent->_table->primaryKey))
1119				{
1120					$pk=is_array($parent->_table->primaryKey) ? $parent->_table->primaryKey[$i] : $parent->_table->primaryKey;
1121					$parentCondition[$pk]=$parent->getColumnPrefix().$schema->quoteColumnName($pk).'='.$joinAlias.'.'.$schema->quoteColumnName($fk);
1122				}
1123				else
1124				{
1125					$j=$i-count($parent->_table->primaryKey);
1126					$pk=is_array($this->_table->primaryKey) ? $this->_table->primaryKey[$j] : $this->_table->primaryKey;
1127					$childCondition[$pk]=$this->getColumnPrefix().$schema->quoteColumnName($pk).'='.$joinAlias.'.'.$schema->quoteColumnName($fk);
1128				}
1129			}
1130		}
1131
1132		if($parentCondition!==array() && $childCondition!==array())
1133		{
1134			$join=$this->relation->joinType.' '.$joinTable->rawName.' '.$joinAlias;
1135			$join.=' ON ('.implode(') AND (',$parentCondition).')';
1136			$join.=' '.$this->relation->joinType.' '.$this->getTableNameWithAlias();
1137			$join.=' ON ('.implode(') AND (',$childCondition).')';
1138			if(!empty($this->relation->on))
1139				$join.=' AND ('.$this->relation->on.')';
1140			return $join;
1141		}
1142		else
1143			throw new CDbException(Yii::t('yii','The relation "{relation}" in active record class "{class}" is specified with an incomplete foreign key. The foreign key must consist of columns referencing both joining tables.',
1144				array('{class}'=>get_class($parent->model), '{relation}'=>$this->relation->name)));
1145	}
1146}
1147
1148
1149/**
1150 * CJoinQuery represents a JOIN SQL statement.
1151 *
1152 * @author Qiang Xue <qiang.xue@gmail.com>
1153 * @package system.db.ar
1154 * @since 1.0
1155 */
1156class CJoinQuery
1157{
1158	/**
1159	 * @var array list of column selections
1160	 */
1161	public $selects=array();
1162	/**
1163	 * @var boolean whether to select distinct result set
1164	 */
1165	public $distinct=false;
1166	/**
1167	 * @var array list of join statement
1168	 */
1169	public $joins=array();
1170	/**
1171	 * @var array list of WHERE clauses
1172	 */
1173	public $conditions=array();
1174	/**
1175	 * @var array list of ORDER BY clauses
1176	 */
1177	public $orders=array();
1178	/**
1179	 * @var array list of GROUP BY clauses
1180	 */
1181	public $groups=array();
1182	/**
1183	 * @var array list of HAVING clauses
1184	 */
1185	public $havings=array();
1186	/**
1187	 * @var integer row limit
1188	 */
1189	public $limit=-1;
1190	/**
1191	 * @var integer row offset
1192	 */
1193	public $offset=-1;
1194	/**
1195	 * @var array list of query parameters
1196	 */
1197	public $params=array();
1198	/**
1199	 * @var array list of join element IDs (id=>true)
1200	 */
1201	public $elements=array();
1202
1203	/**
1204	 * Constructor.
1205	 * @param CJoinElement $joinElement The root join tree.
1206	 * @param CDbCriteria $criteria the query criteria
1207	 */
1208	public function __construct($joinElement,$criteria=null)
1209	{
1210		if($criteria!==null)
1211		{
1212			$this->selects[]=$joinElement->getColumnSelect($criteria->select);
1213			$this->joins[]=$joinElement->getTableNameWithAlias();
1214			$this->joins[]=$criteria->join;
1215			$this->conditions[]=$criteria->condition;
1216			$this->orders[]=$criteria->order;
1217			$this->groups[]=$criteria->group;
1218			$this->havings[]=$criteria->having;
1219			$this->limit=$criteria->limit;
1220			$this->offset=$criteria->offset;
1221			$this->params=$criteria->params;
1222			if(!$this->distinct && $criteria->distinct)
1223				$this->distinct=true;
1224		}
1225		else
1226		{
1227			$this->selects[]=$joinElement->getPrimaryKeySelect();
1228			$this->joins[]=$joinElement->getTableNameWithAlias();
1229			$this->conditions[]=$joinElement->getPrimaryKeyRange();
1230		}
1231		$this->elements[$joinElement->id]=true;
1232	}
1233
1234	/**
1235	 * Joins with another join element
1236	 * @param CJoinElement $element the element to be joined
1237	 */
1238	public function join($element)
1239	{
1240		if($element->slave!==null)
1241			$this->join($element->slave);
1242		if(!empty($element->relation->select))
1243			$this->selects[]=$element->getColumnSelect($element->relation->select);
1244		$this->conditions[]=$element->relation->condition;
1245		$this->orders[]=$element->relation->order;
1246		$this->joins[]=$element->getJoinCondition();
1247		$this->joins[]=$element->relation->join;
1248		$this->groups[]=$element->relation->group;
1249		$this->havings[]=$element->relation->having;
1250
1251		if(is_array($element->relation->params))
1252		{
1253			if(is_array($this->params))
1254				$this->params=array_merge($this->params,$element->relation->params);
1255			else
1256				$this->params=$element->relation->params;
1257		}
1258		$this->elements[$element->id]=true;
1259	}
1260
1261	/**
1262	 * Creates the SQL statement.
1263	 * @param CDbCommandBuilder $builder the command builder
1264	 * @return CDbCommand DB command instance representing the SQL statement
1265	 */
1266	public function createCommand($builder)
1267	{
1268		$sql=($this->distinct ? 'SELECT DISTINCT ':'SELECT ') . implode(', ',$this->selects);
1269		$sql.=' FROM ' . implode(' ',$this->joins);
1270
1271		$conditions=array();
1272		foreach($this->conditions as $condition)
1273			if($condition!=='')
1274				$conditions[]=$condition;
1275		if($conditions!==array())
1276			$sql.=' WHERE (' . implode(') AND (',$conditions).')';
1277
1278		$groups=array();
1279		foreach($this->groups as $group)
1280			if($group!=='')
1281				$groups[]=$group;
1282		if($groups!==array())
1283			$sql.=' GROUP BY ' . implode(', ',$groups);
1284
1285		$havings=array();
1286		foreach($this->havings as $having)
1287			if($having!=='')
1288				$havings[]=$having;
1289		if($havings!==array())
1290			$sql.=' HAVING (' . implode(') AND (',$havings).')';
1291
1292		$orders=array();
1293		foreach($this->orders as $order)
1294			if($order!=='')
1295				$orders[]=$order;
1296		if($orders!==array())
1297			$sql.=' ORDER BY ' . implode(', ',$orders);
1298
1299		$sql=$builder->applyLimit($sql,$this->limit,$this->offset);
1300		$command=$builder->getDbConnection()->createCommand($sql);
1301		$builder->bindValues($command,$this->params);
1302		return $command;
1303	}
1304}
1305
1306
1307/**
1308 * CStatElement represents STAT join element for {@link CActiveFinder}.
1309 *
1310 * @author Qiang Xue <qiang.xue@gmail.com>
1311 * @package system.db.ar
1312 */
1313class CStatElement
1314{
1315	/**
1316	 * @var CActiveRelation the relation represented by this tree node
1317	 */
1318	public $relation;
1319
1320	private $_finder;
1321	private $_parent;
1322
1323	/**
1324	 * Constructor.
1325	 * @param CActiveFinder $finder the finder
1326	 * @param CStatRelation $relation the STAT relation
1327	 * @param CJoinElement $parent the join element owning this STAT element
1328	 */
1329	public function __construct($finder,$relation,$parent)
1330	{
1331		$this->_finder=$finder;
1332		$this->_parent=$parent;
1333		$this->relation=$relation;
1334		$parent->stats[]=$this;
1335	}
1336
1337	/**
1338	 * Performs the STAT query.
1339	 */
1340	public function query()
1341	{
1342		if(preg_match('/^\s*(.*?)\((.*)\)\s*$/',$this->relation->foreignKey,$matches))
1343			$this->queryManyMany($matches[1],$matches[2]);
1344		else
1345			$this->queryOneMany();
1346	}
1347
1348	private function queryOneMany()
1349	{
1350		$relation=$this->relation;
1351		$model=CActiveRecord::model($relation->className);
1352		$builder=$model->getCommandBuilder();
1353		$schema=$builder->getSchema();
1354		$table=$model->getTableSchema();
1355		$parent=$this->_parent;
1356		$pkTable=$parent->model->getTableSchema();
1357
1358		$fks=preg_split('/\s*,\s*/',$relation->foreignKey,-1,PREG_SPLIT_NO_EMPTY);
1359		if(count($fks)!==count($pkTable->primaryKey))
1360			throw new CDbException(Yii::t('yii','The relation "{relation}" in active record class "{class}" is specified with an invalid foreign key. The columns in the key must match the primary keys of the table "{table}".',
1361						array('{class}'=>get_class($parent->model), '{relation}'=>$relation->name, '{table}'=>$pkTable->name)));
1362
1363		// set up mapping between fk and pk columns
1364		$map=array();  // pk=>fk
1365		foreach($fks as $i=>$fk)
1366		{
1367			if(!isset($table->columns[$fk]))
1368				throw new CDbException(Yii::t('yii','The relation "{relation}" in active record class "{class}" is specified with an invalid foreign key "{key}". There is no such column in the table "{table}".',
1369					array('{class}'=>get_class($parent->model), '{relation}'=>$relation->name, '{key}'=>$fk, '{table}'=>$table->name)));
1370
1371			if(isset($table->foreignKeys[$fk]))
1372			{
1373				list($tableName,$pk)=$table->foreignKeys[$fk];
1374				if($schema->compareTableNames($pkTable->rawName,$tableName))
1375					$map[$pk]=$fk;
1376				else
1377					throw new CDbException(Yii::t('yii','The relation "{relation}" in active record class "{class}" is specified with a foreign key "{key}" that does not point to the parent table "{table}".',
1378						array('{class}'=>get_class($parent->model), '{relation}'=>$relation->name, '{key}'=>$fk, '{table}'=>$pkTable->name)));
1379			}
1380			else  // FK constraints undefined
1381			{
1382				if(is_array($pkTable->primaryKey)) // composite PK
1383					$map[$pkTable->primaryKey[$i]]=$fk;
1384				else
1385					$map[$pkTable->primaryKey]=$fk;
1386			}
1387		}
1388
1389		$records=$this->_parent->records;
1390
1391		$join=empty($relation->join)?'' : ' '.$relation->join;
1392		$where=empty($relation->condition)?' WHERE ' : ' WHERE ('.$relation->condition.') AND ';
1393		$group=empty($relation->group)?'' : ', '.$relation->group;
1394		$having=empty($relation->having)?'' : ' HAVING ('.$relation->having.')';
1395		$order=empty($relation->order)?'' : ' ORDER BY '.$relation->order;
1396
1397		$c=$schema->quoteColumnName('c');
1398		$s=$schema->quoteColumnName('s');
1399
1400		$tableAlias=$model->getTableAlias(true);
1401
1402		// generate and perform query
1403		if(count($fks)===1)  // single column FK
1404		{
1405			$col=$table->columns[$fks[0]]->rawName;
1406			$sql="SELECT $col AS $c, {$relation->select} AS $s FROM {$table->rawName} ".$tableAlias.$join
1407				.$where.'('.$builder->createInCondition($table,$fks[0],array_keys($records),$tableAlias.'.').')'
1408				." GROUP BY $col".$group
1409				.$having.$order;
1410			$command=$builder->getDbConnection()->createCommand($sql);
1411			if(is_array($relation->params))
1412				$builder->bindValues($command,$relation->params);
1413			$stats=array();
1414			foreach($command->queryAll() as $row)
1415				$stats[$row['c']]=$row['s'];
1416		}
1417		else  // composite FK
1418		{
1419			$keys=array_keys($records);
1420			foreach($keys as &$key)
1421			{
1422				$key2=unserialize($key);
1423				$key=array();
1424				foreach($pkTable->primaryKey as $pk)
1425					$key[$map[$pk]]=$key2[$pk];
1426			}
1427			$cols=array();
1428			foreach($pkTable->primaryKey as $n=>$pk)
1429			{
1430				$name=$table->columns[$map[$pk]]->rawName;
1431				$cols[$name]=$name.' AS '.$schema->quoteColumnName('c'.$n);
1432			}
1433			$sql='SELECT '.implode(', ',$cols).", {$relation->select} AS $s FROM {$table->rawName} ".$tableAlias.$join
1434				.$where.'('.$builder->createInCondition($table,$fks,$keys,$tableAlias.'.').')'
1435				.' GROUP BY '.implode(', ',array_keys($cols)).$group
1436				.$having.$order;
1437			$command=$builder->getDbConnection()->createCommand($sql);
1438			if(is_array($relation->params))
1439				$builder->bindValues($command,$relation->params);
1440			$stats=array();
1441			foreach($command->queryAll() as $row)
1442			{
1443				$key=array();
1444				foreach($pkTable->primaryKey as $n=>$pk)
1445					$key[$pk]=$row['c'.$n];
1446				$stats[serialize($key)]=$row['s'];
1447			}
1448		}
1449
1450		// populate the results into existing records
1451		foreach($records as $pk=>$record)
1452			$record->addRelatedRecord($relation->name,isset($stats[$pk])?$stats[$pk]:$relation->defaultValue,false);
1453	}
1454
1455	/*
1456	 * @param string $joinTableName jointablename
1457	 * @param string $keys keys
1458	 */
1459	private function queryManyMany($joinTableName,$keys)
1460	{
1461		$relation=$this->relation;
1462		$model=CActiveRecord::model($relation->className);
1463		$table=$model->getTableSchema();
1464		$builder=$model->getCommandBuilder();
1465		$schema=$builder->getSchema();
1466		$pkTable=$this->_parent->model->getTableSchema();
1467
1468		$tableAlias=$model->getTableAlias(true);
1469
1470		if(($joinTable=$builder->getSchema()->getTable($joinTableName))===null)
1471			throw new CDbException(Yii::t('yii','The relation "{relation}" in active record class "{class}" is not specified correctly. The join table "{joinTable}" given in the foreign key cannot be found in the database.',
1472				array('{class}'=>get_class($this->_parent->model), '{relation}'=>$relation->name, '{joinTable}'=>$joinTableName)));
1473
1474		$fks=preg_split('/\s*,\s*/',$keys,-1,PREG_SPLIT_NO_EMPTY);
1475		if(count($fks)!==count($table->primaryKey)+count($pkTable->primaryKey))
1476			throw new CDbException(Yii::t('yii','The relation "{relation}" in active record class "{class}" is specified with an incomplete foreign key. The foreign key must consist of columns referencing both joining tables.',
1477				array('{class}'=>get_class($this->_parent->model), '{relation}'=>$relation->name)));
1478
1479		$joinCondition=array();
1480		$map=array();
1481
1482		$fkDefined=true;
1483		foreach($fks as $i=>$fk)
1484		{
1485			if(!isset($joinTable->columns[$fk]))
1486				throw new CDbException(Yii::t('yii','The relation "{relation}" in active record class "{class}" is specified with an invalid foreign key "{key}". There is no such column in the table "{table}".',
1487					array('{class}'=>get_class($this->_parent->model), '{relation}'=>$relation->name, '{key}'=>$fk, '{table}'=>$joinTable->name)));
1488
1489			if(isset($joinTable->foreignKeys[$fk]))
1490			{
1491				list($tableName,$pk)=$joinTable->foreignKeys[$fk];
1492				if(!isset($joinCondition[$pk]) && $schema->compareTableNames($table->rawName,$tableName))
1493					$joinCondition[$pk]=$tableAlias.'.'.$schema->quoteColumnName($pk).'='.$joinTable->rawName.'.'.$schema->quoteColumnName($fk);
1494				elseif(!isset($map[$pk]) && $schema->compareTableNames($pkTable->rawName,$tableName))
1495					$map[$pk]=$fk;
1496				else
1497				{
1498					$fkDefined=false;
1499					break;
1500				}
1501			}
1502			else
1503			{
1504				$fkDefined=false;
1505				break;
1506			}
1507		}
1508
1509		if(!$fkDefined)
1510		{
1511			$joinCondition=array();
1512			$map=array();
1513			foreach($fks as $i=>$fk)
1514			{
1515				if($i<count($pkTable->primaryKey))
1516				{
1517					$pk=is_array($pkTable->primaryKey) ? $pkTable->primaryKey[$i] : $pkTable->primaryKey;
1518					$map[$pk]=$fk;
1519				}
1520				else
1521				{
1522					$j=$i-count($pkTable->primaryKey);
1523					$pk=is_array($table->primaryKey) ? $table->primaryKey[$j] : $table->primaryKey;
1524					$joinCondition[$pk]=$tableAlias.'.'.$schema->quoteColumnName($pk).'='.$joinTable->rawName.'.'.$schema->quoteColumnName($fk);
1525				}
1526			}
1527		}
1528
1529		if($joinCondition===array() || $map===array())
1530			throw new CDbException(Yii::t('yii','The relation "{relation}" in active record class "{class}" is specified with an incomplete foreign key. The foreign key must consist of columns referencing both joining tables.',
1531				array('{class}'=>get_class($this->_parent->model), '{relation}'=>$relation->name)));
1532
1533		$records=$this->_parent->records;
1534
1535		$cols=array();
1536		foreach(is_string($pkTable->primaryKey)?array($pkTable->primaryKey):$pkTable->primaryKey as $n=>$pk)
1537		{
1538			$name=$joinTable->rawName.'.'.$schema->quoteColumnName($map[$pk]);
1539			$cols[$name]=$name.' AS '.$schema->quoteColumnName('c'.$n);
1540		}
1541
1542		$keys=array_keys($records);
1543		if(is_array($pkTable->primaryKey))
1544		{
1545			foreach($keys as &$key)
1546			{
1547				$key2=unserialize($key);
1548				$key=array();
1549				foreach($pkTable->primaryKey as $pk)
1550					$key[$map[$pk]]=$key2[$pk];
1551			}
1552		}
1553
1554		$join=empty($relation->join)?'' : ' '.$relation->join;
1555		$where=empty($relation->condition)?'' : ' WHERE ('.$relation->condition.')';
1556		$group=empty($relation->group)?'' : ', '.$relation->group;
1557		$having=empty($relation->having)?'' : ' AND ('.$relation->having.')';
1558		$order=empty($relation->order)?'' : ' ORDER BY '.$relation->order;
1559
1560		$sql='SELECT '.$this->relation->select.' AS '.$schema->quoteColumnName('s').', '.implode(', ',$cols)
1561			.' FROM '.$table->rawName.' '.$tableAlias.' INNER JOIN '.$joinTable->rawName
1562			.' ON ('.implode(') AND (',$joinCondition).')'.$join
1563			.$where
1564			.' GROUP BY '.implode(', ',array_keys($cols)).$group
1565			.' HAVING ('.$builder->createInCondition($joinTable,$map,$keys).')'
1566			.$having.$order;
1567
1568		$command=$builder->getDbConnection()->createCommand($sql);
1569		if(is_array($relation->params))
1570			$builder->bindValues($command,$relation->params);
1571
1572		$stats=array();
1573		foreach($command->queryAll() as $row)
1574		{
1575			if(is_array($pkTable->primaryKey))
1576			{
1577				$key=array();
1578				foreach($pkTable->primaryKey as $n=>$k)
1579					$key[$k]=$row['c'.$n];
1580				$stats[serialize($key)]=$row['s'];
1581			}
1582			else
1583				$stats[$row['c0']]=$row['s'];
1584		}
1585
1586		foreach($records as $pk=>$record)
1587			$record->addRelatedRecord($relation->name,isset($stats[$pk])?$stats[$pk]:$this->

Large files files are truncated, but you can click here to view the full file