Skip to content
Permalink
Browse files

Refactor out common code.

Create a helper method that appends the junction join to a query.
  • Loading branch information...
markstory committed Dec 6, 2015
1 parent 57bd5ef commit 963965ca6d8c3698e445437466cb4ed509a7ad52
Showing with 30 additions and 26 deletions.
  1. +30 −26 src/ORM/Association/BelongsToMany.php
@@ -794,21 +794,37 @@ public function find($type = null, array $options = [])
return $query;
}
$junction = $this->junction();
$target = $this->target();
$belongsTo = $junction->association($target->alias());
$belongsTo = $this->junction()->association($this->target()->alias());
$conditions = $belongsTo->_joinCondition([
'foreignKey' => $this->foreignKey()
]);
$join = [
'table' => $junction->table(),
'conditions' => $conditions,
'type' => 'INNER'
];
return $this->_appendJunctionJoin($query, $conditions);
}
/**
* Append a join to the junction table.
*
* @param \Cake\ORM\Query $query The query to append.
* @param string|array $conditions The query conditions to use.
* @return \Cake\ORM\Query The modified query.
*/
protected function _appendJunctionJoin($query, $conditions)
{
$name = $this->_junctionAssociationName();
$query->join([$name => $join]);
$query->eagerLoader()->addToJoinsMap($name, $belongsTo);
$joins = $query->join();
$matching = [
$name => [
'table' => $this->junction()->table(),
'conditions' => $conditions,
'type' => 'INNER'
]
];
$assoc = $this->target()->association($name);
$query
->addDefaultTypes($assoc->target())
->join($matching + $joins, [], true);
$query->eagerLoader()->addToJoinsMap($name, $assoc);
return $query;
}
@@ -1081,25 +1097,13 @@ protected function _buildQuery($options)
$name = $this->_junctionAssociationName();
$query = $this->_buildBaseQuery($options);
$joins = $query->join();
$keys = $this->_linkField($options);
$matching = [
$name => [
'table' => $this->junction()->table(),
'conditions' => $keys,
'type' => 'INNER'
]
];
$query = $this->_appendJunctionJoin($query, $keys);
$assoc = $this->target()->association($name);
$query
->addDefaultTypes($assoc->target())
->join($matching + $joins, [], true)
->autoFields($query->clause('select') === [])
$query->autoFields($query->clause('select') === [])
->select($query->aliasFields((array)$assoc->foreignKey(), $name));
$query->eagerLoader()->addToJoinsMap($name, $assoc);
$assoc->attachTo($query);
return $query;
}

0 comments on commit 963965c

Please sign in to comment.
You can’t perform that action at this time.