public function join($target, $type = 'LEFT', $alias = null, $relationId = null)
{
$this->explictSelect = true;
$query = $this->getCurrentReadQuery();
// for models and schemas join
if (is_object($target)) {
$table = $target->getTable();
/* XXX: should get selected column names by default, if not get all column names */
$columns = $target->getColumnNames();
$joinAlias = $alias ?: $table;
if (!empty($columns)) {
$select = array();
foreach ($columns as $name) {
// Select alias.column as alias_column
$select[$joinAlias . '.' . $name] = $joinAlias . '_' . $name;
}
$query->select($select);
}
$joinExpr = $query->join($table, $joinAlias, $type);
// it returns JoinExpression object
// here the relationship is defined, join the it.
if ($relationId) {
if ($relation = $this->getSchema()->getRelation($relationId)) {
$joinExpr->on()->equal($this->_alias . '.' . $relation['self_column'], array($joinAlias . '.' . $relation['foreign_column']));
} else {
throw new Exception("Relationship '{$relationId}' not found.");
}
} else {
// find the related relatinship from defined relatinpships
$relations = $this->getSchema()->relations;
foreach ($relations as $relationId => $relation) {
if (!isset($relation['foreign_schema'])) {
continue;
}
$fschema = new $relation['foreign_schema']();
if (is_a($target, $fschema->getModelClass())) {
$joinExpr->on()->equal($this->_alias . '.' . $relation['self_column'], array($alias . '.' . $relation['foreign_column']));
break;
}
}
}
if ($joinAlias) {
$joinExpr->as($joinAlias);
}
return $joinExpr;
} else {
// For table name join
$joinExpr = $query->join($target, $type);
if ($alias) {
$joinExpr->as($alias);
}
return $joinExpr;
}
}