Browse Source

Fixed contain() BelongsToMany association restricting fields with 'fields' option

Backport changes from #14141 to 3.x
Corey Taylor 6 years ago
parent
commit
3a7c7027e0

+ 8 - 0
src/ORM/Association/Loader/SelectWithPivotLoader.php

@@ -128,6 +128,14 @@ class SelectWithPivotLoader extends SelectLoader
     }
 
     /**
+     * @inheritDoc
+     */
+    protected function _assertFieldsPresent(Query $fetchQuery, array $key): void
+    {
+        // _buildQuery() manually adds in required fields from junction table
+    }
+
+    /**
      * Generates a string used as a table field that contains the values upon
      * which the filter should be applied
      *

+ 13 - 0
tests/TestCase/ORM/Association/BelongsToManyTest.php

@@ -1280,6 +1280,19 @@ class BelongsToManyTest extends TestCase
 
         $this->assertNotEmpty($result->tags[0]->id);
         $this->assertEmpty($result->tags[0]->name);
+
+        $result = $table
+            ->find()
+            ->contain([
+                'Tags' => [
+                    'fields' => [
+                        'Tags.name',
+                    ],
+                ],
+            ])
+            ->first();
+        $this->assertNotEmpty($result->tags[0]->name);
+        $this->assertEmpty($result->tags[0]->id);
     }
 
     /**

+ 3 - 1
tests/TestCase/ORM/QueryRegressionTest.php

@@ -154,12 +154,14 @@ class QueryRegressionTest extends TestCase
      */
     public function testEagerLoadingBelongsToManyList()
     {
-        $this->expectException(\InvalidArgumentException::class);
         $this->loadFixtures('Articles', 'Tags', 'ArticlesTags');
         $table = $this->getTableLocator()->get('Articles');
         $table->belongsToMany('Tags', [
             'finder' => 'list',
         ]);
+
+        $this->expectException(\RuntimeException::class);
+        $this->expectExceptionMessage('"_joinData" is missing from the belongsToMany results');
         $table->find()->contain('Tags')->toArray();
     }