Skip to content

Commit

Permalink
Fix belongsToMany with deeper associations not loading.
Browse files Browse the repository at this point in the history
When deep associations are loaded from junction tables, they are loaded
as a hasMany. This means we need to accomodate for this structure as
well.

This solution doesn't make me happy but it was the smallest change
I could make. Other approaches I took caused other things to break.
  • Loading branch information
markstory authored and lorenzo committed Aug 6, 2016
1 parent f67d786 commit d785d98
Showing 1 changed file with 14 additions and 2 deletions.
16 changes: 14 additions & 2 deletions src/ORM/Association/BelongsToMany.php
Expand Up @@ -468,7 +468,14 @@ protected function _buildResultMap($fetchQuery, $options)
$property
));
}
$result[$this->_junctionProperty] = $result[$property];
$junctionData = $result[$property];

// Account for incorrectly nested data from hasMany
// bindings when junction tables have additional associations loaded
if (isset($result[$property][0])) {
$junctionData = $result[$property][0];
}
$result[$this->_junctionProperty] = $junctionData;
unset($result[$property]);

if ($hydrated) {
Expand Down Expand Up @@ -1282,7 +1289,12 @@ protected function _buildQuery($options)
->where($this->junctionConditions())
->select($query->aliasFields((array)$assoc->foreignKey(), $name));

$assoc->attachTo($query);
// If this hasMany attaches any other containments, then the junction
// table is queried twice. Ideally the EagerLoader could resolve the duplication,
// and merge the resulting eagerloadable instances.
//
// We have to define aliasPath, so any nested contains will work.
$assoc->attachTo($query, ['aliasPath' => $assoc->alias()]);

return $query;
}
Expand Down

0 comments on commit d785d98

Please sign in to comment.