diff --git a/src/ORM/Association/BelongsToMany.php b/src/ORM/Association/BelongsToMany.php index 26178ca5cbf..4feeb8b070b 100644 --- a/src/ORM/Association/BelongsToMany.php +++ b/src/ORM/Association/BelongsToMany.php @@ -1204,13 +1204,18 @@ protected function _buildQuery($options) } $query = $this->_appendJunctionJoin($query, []); + + if ($query->autoFields() === null) { + $query->autoFields($query->clause('select') === []); + } + // Ensure that association conditions are applied // and that the required keys are in the selected columns. $query ->where($this->junctionConditions()) - ->autoFields($query->clause('select') === []) ->select($query->aliasFields((array)$assoc->foreignKey(), $name)); + $assoc->attachTo($query); return $query; } diff --git a/tests/TestCase/ORM/Association/BelongsToManyTest.php b/tests/TestCase/ORM/Association/BelongsToManyTest.php index 5c3f905a6b2..9c88fa5db28 100644 --- a/tests/TestCase/ORM/Association/BelongsToManyTest.php +++ b/tests/TestCase/ORM/Association/BelongsToManyTest.php @@ -980,6 +980,27 @@ public function testEagerLoadingBelongsToManyLimitedFields() $this->assertEmpty($result->tags[0]->name); } + /** + * Tests that fetching belongsToMany association will retain autoFields(true) if it was used. + * + * @see https://github.com/cakephp/cakephp/issues/8052 + * @return void + */ + public function testEagerLoadingBelongsToManyLimitedFieldsWithAutoFields() + { + $table = TableRegistry::get('Articles'); + $table->belongsToMany('Tags'); + $result = $table + ->find() + ->contain(['Tags' => function ($q) { + return $q->select(['two' => '1 + 1'])->autoFields(true); + }]) + ->first(); + + $this->assertNotEmpty($result->tags[0]->two, 'Should have computed field'); + $this->assertNotEmpty($result->tags[0]->name, 'Should have standard field'); + } + /** * Test that association proxy find() applies joins when conditions are involved. *