public function fetchRelatedFor(Doctrine_Record $record)
{
$id = $record->getIncremented();
if (empty($id) || !$this->definition['table']->getAttribute(Doctrine_Core::ATTR_LOAD_REFERENCES)) {
return Doctrine_Collection::create($this->getTable());
} else {
$q = new Doctrine_RawSql($this->getTable()->getConnection());
$assocTable = $this->getAssociationFactory()->getTableName();
$tableName = $record->getTable()->getTableName();
$identifierColumnNames = $record->getTable()->getIdentifierColumnNames();
$identifier = array_pop($identifierColumnNames);
$sub = 'SELECT ' . $this->getForeignRefColumnName() . ' FROM ' . $assocTable . ' WHERE ' . $this->getLocalRefColumnName() . ' = ?';
$condition[] = $tableName . '.' . $identifier . ' IN (' . $sub . ')';
$joinCondition[] = $tableName . '.' . $identifier . ' = ' . $assocTable . '.' . $this->getForeignRefColumnName();
if ($this->definition['equal']) {
$sub2 = 'SELECT ' . $this->getLocalRefColumnName() . ' FROM ' . $assocTable . ' WHERE ' . $this->getForeignRefColumnName() . ' = ?';
$condition[] = $tableName . '.' . $identifier . ' IN (' . $sub2 . ')';
$joinCondition[] = $tableName . '.' . $identifier . ' = ' . $assocTable . '.' . $this->getLocalRefColumnName();
}
$q->select('{' . $tableName . '.*}, {' . $assocTable . '.*}')->from($tableName . ' INNER JOIN ' . $assocTable . ' ON ' . implode(' OR ', $joinCondition))->where(implode(' OR ', $condition))->orderBy($tableName . '.' . $identifier . ' ASC');
if ($orderBy = $this->getOrderByStatement($tableName, true)) {
$q->addOrderBy($orderBy);
}
$q->addComponent($tableName, $this->getClass());
$path = $this->getClass() . '.' . $this->getAssociationFactory()->getComponentName();
if ($this->definition['refClassRelationAlias']) {
$path = $this->getClass() . '.' . $this->definition['refClassRelationAlias'];
}
$q->addComponent($assocTable, $path);
$params = $this->definition['equal'] ? array($id, $id) : array($id);
$res = $q->execute($params);
return $res;
}
}