Skip to content

Commit

Permalink
ActiveRow: added support to update primary columns via update() [Closes
Browse files Browse the repository at this point in the history
#57][Closes #58]
  • Loading branch information
Martin Dendis authored and dg committed Mar 26, 2015
1 parent 0676795 commit e057c95
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 1 deletion.
15 changes: 14 additions & 1 deletion src/Database/Table/ActiveRow.php
Original file line number Diff line number Diff line change
Expand Up @@ -167,10 +167,23 @@ public function related($key, $throughColumn = NULL)
*/
public function update($data)
{
if ($data instanceof \Traversable) {
$data = iterator_to_array($data);
}

$primary = $this->getPrimary();
if (!is_array($primary)) {
$primary = array($this->table->getPrimary() => $primary);
}

$selection = $this->table->createSelectionInstance()
->wherePrimary($this->getPrimary());
->wherePrimary($primary);

if ($selection->update($data)) {
if ($tmp = array_intersect_key($data, $primary)) {
$selection = $this->table->createSelectionInstance()
->wherePrimary($tmp + $primary);
}
$selection->select('*');
if (($row = $selection->fetch()) === FALSE) {
throw new Nette\InvalidStateException('Database refetch failed; row does not exist!');
Expand Down
20 changes: 20 additions & 0 deletions tests/Database/Table/Table.update().phpt
Original file line number Diff line number Diff line change
Expand Up @@ -68,3 +68,23 @@ $bookTag = $book2->related('book_tag')->insert(array(
$app = $context->table('book')->get(5); // SELECT * FROM `book` WHERE (`id` = ?)
$tags = iterator_to_array($app->related('book_tag')); // SELECT * FROM `book_tag` WHERE (`book_tag`.`book_id` IN (5))
Assert::same('Xbox Game', reset($tags)->tag->name); // SELECT * FROM `tag` WHERE (`tag`.`id` IN (24))


$tag2 = $context->table('tag')->insert(array(
'name' => 'PS4 Game',
)); // INSERT INTO `tag` (`name`) VALUES ('PS4 Game')

$tag2->update(array(
'id' => 1,
)); // UPDATE `tag` SET `id`=1 WHERE (`id` = (?))
Assert::same(1, $tag2->id);


$book_tag = $context->table('book_tag')->get(array(
'book_id' => 5,
'tag_id' => 25,
)); // SELECT * FROM `book_tag` WHERE (`book_id` = (?) AND `tag_id` = (?))
$book_tag->update(new ArrayIterator(array(
'tag_id' => 21,
))); // UPDATE `book_tag` SET `tag_id`=21 WHERE (`book_id` = (?) AND `tag_id` = (?))
Assert::same(21, $book_tag->tag_id);

0 comments on commit e057c95

Please sign in to comment.