Browse Source

Don't set associated record to null when autofields is disabled.

ADmad 9 years ago
parent
commit
e084a14488
2 changed files with 42 additions and 1 deletions
  1. 9 1
      src/ORM/ResultSet.php
  2. 33 0
      tests/TestCase/ORM/ResultSetTest.php

+ 9 - 1
src/ORM/ResultSet.php

@@ -122,6 +122,13 @@ class ResultSet implements ResultSetInterface
     protected $_hydrate = true;
 
     /**
+     * Tracks value of $_autoFields property of $query passed to constructor.
+     *
+     * @var bool
+     */
+    protected $_autoFields;
+
+    /**
      * The fully namespaced name of the class to use for hydrating results
      *
      * @var string
@@ -179,6 +186,7 @@ class ResultSet implements ResultSetInterface
         $this->_defaultAlias = $this->_defaultTable->alias();
         $this->_calculateColumnMap($query);
         $this->_calculateTypeMap();
+        $this->_autoFields = $query->autoFields();
 
         if ($this->_useBuffering) {
             $count = $this->count();
@@ -525,7 +533,7 @@ class ResultSet implements ResultSetInterface
             $options['source'] = $target->registryAlias();
             unset($presentAliases[$alias]);
 
-            if ($assoc['canBeJoined']) {
+            if ($assoc['canBeJoined'] && $this->_autoFields !== false) {
                 $hasData = false;
                 foreach ($results[$alias] as $v) {
                     if ($v !== null && $v !== []) {

+ 33 - 0
tests/TestCase/ORM/ResultSetTest.php

@@ -292,6 +292,39 @@ class ResultSetTest extends TestCase
     }
 
     /**
+     * Test showing associated record is preserved when selecting only field with
+     * null value if auto fields is disabled.
+     *
+     * @return void
+     */
+    public function testBelongsToEagerLoaderWithAutoFieldsFalse()
+    {
+        $authors = TableRegistry::get('Authors');
+
+        $author = $authors->newEntity(['name' => null]);
+        $authors->save($author);
+
+        $articles = TableRegistry::get('Articles');
+        $articles->belongsTo('Authors');
+
+        $article = $articles->newEntity([
+            'author_id' => $author->id,
+            'title' => 'article with author with null name'
+        ]);
+        $articles->save($article);
+
+        $result = $articles->find()
+            ->select(['Articles.id', 'Articles.title', 'Authors.name'])
+            ->contain(['Authors'])
+            ->where(['Articles.id' => $article->id])
+            ->autoFields(false)
+            ->hydrate(false)
+            ->first();
+
+        $this->assertNotNull($result['author']);
+    }
+
+    /**
      * Test that eagerLoader leaves empty associations unpopulated.
      *
      * @return void