diff --git a/src/ORM/Association/BelongsToMany.php b/src/ORM/Association/BelongsToMany.php index d4c2fcc620a..cd4d12b8d2b 100644 --- a/src/ORM/Association/BelongsToMany.php +++ b/src/ORM/Association/BelongsToMany.php @@ -1285,7 +1285,11 @@ protected function _buildQuery($options) $query ->eagerLoader() ->addToJoinsMap($tempName, $assoc, false, $this->_junctionProperty); - $assoc->attachTo($query, ['aliasPath' => $assoc->alias(), 'includeFields' => false]); + $assoc->attachTo($query, [ + 'aliasPath' => $assoc->alias(), + 'includeFields' => false, + 'propertyPath' => $this->_junctionProperty + ]); return $query; } diff --git a/tests/TestCase/ORM/QueryTest.php b/tests/TestCase/ORM/QueryTest.php index 34a87a41d9c..3659cc20f85 100644 --- a/tests/TestCase/ORM/QueryTest.php +++ b/tests/TestCase/ORM/QueryTest.php @@ -1312,7 +1312,10 @@ public function testFormatResultsBelongsToMany() ->eventManager() ->attach(function ($event, $query) { $query->formatResults(function ($results) { - $results->beforeFind = true; + foreach ($results as $result) { + $result->beforeFind = true; + } + return $results; }); }, 'Model.beforeFind'); @@ -1333,10 +1336,13 @@ public function testFormatResultsBelongsToMany() $expected = [ 'id' => 1, 'name' => 'tag1', - '_joinData' => ['article_id' => 1, 'tag_id' => 1], + '_joinData' => [ + 'article_id' => 1, + 'tag_id' => 1, + 'beforeFind' => true, + ], 'description' => 'A big description', 'created' => new Time('2016-01-01 00:00'), - 'beforeFind' => true, ]; $this->assertEquals($expected, $first->tags[0]->toArray()); $this->assertInstanceOf(Time::class, $first->tags[0]->created); @@ -1344,10 +1350,13 @@ public function testFormatResultsBelongsToMany() $expected = [ 'id' => 2, 'name' => 'tag2', - '_joinData' => ['article_id' => 1, 'tag_id' => 2], + '_joinData' => [ + 'article_id' => 1, + 'tag_id' => 2, + 'beforeFind' => true, + ], 'description' => 'Another big description', 'created' => new Time('2016-01-01 00:00'), - 'beforeFind' => true, ]; $this->assertEquals($expected, $first->tags[1]->toArray()); $this->assertInstanceOf(Time::class, $first->tags[0]->created);