Skip to content

Commit

Permalink
Inverted the order in which the joins for belongsToMany are added
Browse files Browse the repository at this point in the history
  • Loading branch information
lorenzo committed Jun 25, 2016
1 parent 4aab2bf commit c55d553
Showing 1 changed file with 10 additions and 6 deletions.
16 changes: 10 additions & 6 deletions src/ORM/Association/BelongsToMany.php
Expand Up @@ -330,8 +330,6 @@ protected function _generateJunctionAssociations($junction, $source, $target)
*/
public function attachTo(Query $query, array $options = [])
{
parent::attachTo($query, $options);

$junction = $this->junction();
$belongsTo = $junction->association($this->source()->alias());
$cond = $belongsTo->_joinCondition(['foreignKey' => $belongsTo->foreignKey()]);
Expand All @@ -344,14 +342,20 @@ public function attachTo(Query $query, array $options = [])
// Attach the junction table as well we need it to populate _joinData.
$assoc = $this->_targetTable->association($junction->alias());
$query->removeJoin($assoc->name());
$options = array_intersect_key($options, ['joinType' => 1, 'fields' => 1]);
$options += [
$newOptions = array_intersect_key($options, ['joinType' => 1, 'fields' => 1]);
$newOptions += [
'conditions' => $cond,
'includeFields' => $includeFields,
'foreignKey' => $this->targetForeignKey(),
'foreignKey' => false,
];
$assoc->attachTo($query, $options);
$assoc->attachTo($query, $newOptions);
$query->eagerLoader()->addToJoinsMap($junction->alias(), $assoc, true);

parent::attachTo($query, $options);

$foreignKey = $this->targetForeignKey();
$thisJoin = $query->clause('join')[$this->name()];
$thisJoin['conditions']->add($assoc->_joinCondition(['foreignKey' => $foreignKey]));
}

/**
Expand Down

0 comments on commit c55d553

Please sign in to comment.