Skip to content
Permalink
Browse files

Super simplistic version of Table::save()

  • Loading branch information...
lorenzo committed Oct 20, 2013
1 parent a1889f3 commit 61d23448647e7dc15b7e13a2dcc777724a5b3952
Showing with 38 additions and 1 deletion.
  1. +1 −1 Cake/ORM/Association/BelongsToMany.php
  2. +18 −0 Cake/ORM/Table.php
  3. +19 −0 Cake/Test/TestCase/ORM/TableTest.php
@@ -221,7 +221,7 @@ public function eagerLoader(array $options) {
* Appends any conditions required to load the relevant set of records in the
* target table query given a filter key and some filtering values.
*
* @param \Cake\ORM\Query taget table's query
* @param \Cake\ORM\Query target table's query
* @param string $key the fields that should be used for filtering
* @param mixed $filter the value that should be used to match for $key
* @return \Cake\ORM\Query
@@ -23,6 +23,7 @@
use Cake\ORM\Association\BelongsToMany;
use Cake\ORM\Association\HasMany;
use Cake\ORM\Association\HasOne;
use Cake\ORM\Entity;
use Cake\Utility\Inflector;
/**
@@ -772,6 +773,23 @@ public function deleteAll($conditions) {
return $statement->rowCount() > 0;
}
public function save(Entity $entity, $options = []) {
$data = $entity->toArray();
$schema = $this->schema();
$data = array_intersect_key($data, array_flip($schema->columns()));
$query = $this->_buildQuery();
$statement = $query->insert($this->table(), array_keys($data))
->values($data)
->executeStatement();
if ($statement->rowCount() > 0) {
$id = $this->connection()->lastInsertId($this->table());
$entity->set($this->primaryKey(), $id);
}
return $entity;
}
/**
* Calls a finder method directly and applies it to the passed query,
* if no query is passed a new one will be created and returned
@@ -937,4 +937,23 @@ public function testReciprocalBelongsToMany() {
$this->assertInstanceOf('TestApp\Model\Entity\ArticlesTag', $result->tags[0]->extraInfo);
}
/**
* Tests that it is possible to insert a new row using the save method
*
* @return void
*/
public function testSaveNewEntity() {
$entity = new \Cake\ORM\Entity([
'username' => 'superuser',
'password' => 'root',
'created' => new \DateTime('2013-10-10 00:00'),
'updated' => new \DateTime('2013-10-10 00:00')
]);
$table = Table::build('user');
$this->assertSame($entity, $table->save($entity));
$this->assertEquals($entity->id, 5);
$row = $table->find('all')->where(['id' => 5])->first();
$this->assertEquals($entity->toArray(), $row->toArray());
}
}

2 comments on commit 61d2344

@markstory

This comment has been minimized.

Copy link
Member

markstory replied Oct 21, 2013

I'm guessing this is mostly prototype code. But it is nice to see the simple happy path is easy.

@lorenzo

This comment has been minimized.

Copy link
Member Author

lorenzo replied Oct 21, 2013

Whoops, this was not supposed to go to 3.0 yet, it was just a prototype for the branch I'm doing

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