Skip to content
Permalink
Browse files

Preserving the association conditions when using ExistsIn

Closes #7968
  • Loading branch information...
lorenzo committed Mar 5, 2016
1 parent 8d7400d commit 0a434e4e7484ca89c9557672ac0859f891df33b9
Showing with 51 additions and 10 deletions.
  1. +19 −0 src/ORM/Association.php
  2. +8 −10 src/ORM/Rule/ExistsIn.php
  3. +24 −0 tests/TestCase/ORM/RulesCheckerIntegrationTest.php
@@ -678,6 +678,25 @@ public function find($type = null, array $options = [])
->where($this->conditions());
}
/**
* Proxies the operation to the target table's exists method after
* appending the default conditions for thisassociation
*
* @param array|callable|ExpressionInterface $conditions The conditions to use
* for checking if any record matches.
* @see \Cake\ORM\Table::exists()
* @return bool
*/
public function exists($conditions)
{
if (!empty($this->_conditions)) {
$conditions = $this
->find('all', ['conditions' => $conditions])
->clause('where');
}
return $this->target()->exists($conditions);
}
/**
* Proxies the update operation to the target table's updateAll method
*
@@ -77,22 +77,20 @@ public function __invoke(EntityInterface $entity, array $options)
}
$source = $target = $this->_repository;
$isAssociation = $target instanceof Association;
$bindingKey = $isAssociation ? (array)$target->bindingKey() : (array)$target->primaryKey();
$realTarget = $isAssociation ? $target->target() : $target;
if (!empty($options['_sourceTable']) && $realTarget === $options['_sourceTable']) {
return true;
}
if (!empty($options['repository'])) {
$source = $options['repository'];
}
if ($source instanceof Association) {
$source = $source->source();
}
if ($target instanceof Association) {
$bindingKey = (array)$target->bindingKey();
$target = $target->target();
} else {
$bindingKey = (array)$target->primaryKey();
}
if (!empty($options['_sourceTable']) && $target === $options['_sourceTable']) {
return true;
}
if (!$entity->extract($this->_fields, true)) {
return true;
@@ -860,4 +860,28 @@ public function testAvoidExistsInOnAutomaticSaving()
$this->assertSame($entity, $table->save($entity));
}
/**
* Tests the existsIn domain rule respects the conditions set for the associations
*
* @group save
* @return void
*/
public function testExistsInDomainRuleWithAssociationConditions()
{
$entity = new Entity([
'title' => 'An Article',
'author_id' => 1
]);
$table = TableRegistry::get('Articles');
$table->belongsTo('Authors', [
'conditions' => ['Authors.name !=' => 'mariano']
]);
$rules = $table->rulesChecker();
$rules->add($rules->existsIn('author_id', 'Authors'));
$this->assertFalse($table->save($entity));
$this->assertEquals(['_existsIn' => 'This value does not exist'], $entity->errors('author_id'));
}
}

0 comments on commit 0a434e4

Please sign in to comment.
You can’t perform that action at this time.