Skip to content
Permalink
Browse files

Implemented save for hasOne

  • Loading branch information...
lorenzo committed Nov 23, 2013
1 parent dbeee9d commit abc1b4e344cc731ca72719252e3f60017775e33b
Showing with 73 additions and 1 deletion.
  1. +1 −1 Cake/ORM/Association/BelongsTo.php
  2. +16 −0 Cake/ORM/Association/HasOne.php
  3. +56 −0 Cake/Test/TestCase/ORM/TableTest.php
@@ -110,7 +110,7 @@ public function save(Entity $entity, $options = []) {
if (!$targetEntity) {
return $entity;
}
$table = $this->target();
$targetEntity = $table->save($targetEntity, $options);
if (!$targetEntity) {
@@ -103,6 +103,22 @@ public function isOwningSide() {
* @see Table::save()
*/
public function save(Entity $entity, $options = []) {
$targetEntity = $entity->get($this->property());
if (!$targetEntity) {
return $entity;
}
$properties = array_combine(
(array)$this->foreignKey(),
$entity->extract((array)$this->source()->primaryKey())
);
$targetEntity->set($properties);
if (!$this->target()->save($targetEntity, $options)) {
$targetEntity->unsetProperty(array_keys($properties));
return false;
}
return $entity;
}
@@ -1994,4 +1994,60 @@ public function testsSaveBelongsToWithValidationError() {
$this->assertNotEmpty($entity->author->errors('name'));
}
/**
* Tests saving hasOne association
*
* @group save
* @return void
*/
public function testSaveHasOne() {
$entity = new \Cake\ORM\Entity([
'name' => 'Jose'
]);
$entity->article = new \Cake\ORM\Entity([
'title' => 'A Title',
'body' => 'A body'
]);
$table = TableRegistry::get('authors');
$table->hasOne('articles');
$this->assertSame($entity, $table->save($entity));
$this->assertFalse($entity->isNew());
$this->assertFalse($entity->article->isNew());
$this->assertEquals(4, $entity->article->id);
$this->assertEquals(5, $entity->article->get('author_id'));
$this->assertFalse($entity->article->dirty('author_id'));
}
/**
* Tests saving hasOne association and returning a validation error will
* abort the saving process
*
* @group save
* @return void
*/
public function testSaveHasOneWithValidationError() {
$entity = new \Cake\ORM\Entity([
'name' => 'Jose'
]);
$entity->article = new \Cake\ORM\Entity([
'title' => 'A Title',
'body' => 'A body'
]);
$table = TableRegistry::get('authors');
$table->hasOne('articles');
$table->association('articles')
->target()
->validator()
->add('title', 'num', ['rule' => 'numeric']);
$this->assertFalse($table->save($entity));
$this->assertFalse($entity->isNew());
$this->assertTrue($entity->article->isNew());
$this->assertNull($entity->article->id);
$this->assertNull($entity->article->get('author_id'));
$this->assertTrue($entity->article->dirty('author_id'));
$this->assertNotEMpty($entity->article->errors('title'));
}
}

0 comments on commit abc1b4e

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