Browse Source

Make ExistsIn rule work with nullable columns.

If a column is nullable, ExistsIn will allow the foreign key to be null
if all the values in the entity are null.

Refs #5853
Mark Story 11 years ago
parent
commit
49465ec929
2 changed files with 32 additions and 0 deletions
  1. 11 0
      src/ORM/Rule/ExistsIn.php
  2. 21 0
      tests/TestCase/ORM/RulesCheckerIntegrationTest.php

+ 11 - 0
src/ORM/Rule/ExistsIn.php

@@ -78,6 +78,17 @@ class ExistsIn
             return true;
         }
 
+        $nulls = 0;
+        $schema = $this->_repository->schema();
+        foreach ($this->_fields as $field) {
+            if ($schema->isNullable($field) && $entity->get($field) === null) {
+                $nulls++;
+            }
+        }
+        if ($nulls === count($this->_fields)) {
+            return true;
+        }
+
         $conditions = array_combine(
             (array)$this->_repository->primaryKey(),
             $entity->extract($this->_fields)

+ 21 - 0
tests/TestCase/ORM/RulesCheckerIntegrationTest.php

@@ -401,6 +401,27 @@ class RulesCheckerIntegrationTest extends TestCase
     }
 
     /**
+     * ExistsIn uses the schema to verify that nullable fields are ok.
+     *
+     * @return
+     */
+    public function testExistsInNullValue()
+    {
+        $entity = new Entity([
+            'title' => 'An Article',
+            'author_id' => null
+        ]);
+
+        $table = TableRegistry::get('Articles');
+        $table->belongsTo('Authors');
+        $rules = $table->rulesChecker();
+        $rules->add($rules->existsIn('author_id', 'Authors'));
+
+        $this->assertEquals($entity, $table->save($entity));
+        $this->assertEquals([], $entity->errors('author_id'));
+    }
+
+    /**
      * Tests the checkRules save option
      *
      * @group save