Skip to content

Commit e057c95

Browse files
Martin Dendisdg
authored andcommitted
ActiveRow: added support to update primary columns via update() [Closes #57][Closes #58]
1 parent 0676795 commit e057c95

File tree

2 files changed

+34
-1
lines changed

2 files changed

+34
-1
lines changed

src/Database/Table/ActiveRow.php

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -167,10 +167,23 @@ public function related($key, $throughColumn = NULL)
167167
*/
168168
public function update($data)
169169
{
170+
if ($data instanceof \Traversable) {
171+
$data = iterator_to_array($data);
172+
}
173+
174+
$primary = $this->getPrimary();
175+
if (!is_array($primary)) {
176+
$primary = array($this->table->getPrimary() => $primary);
177+
}
178+
170179
$selection = $this->table->createSelectionInstance()
171-
->wherePrimary($this->getPrimary());
180+
->wherePrimary($primary);
172181

173182
if ($selection->update($data)) {
183+
if ($tmp = array_intersect_key($data, $primary)) {
184+
$selection = $this->table->createSelectionInstance()
185+
->wherePrimary($tmp + $primary);
186+
}
174187
$selection->select('*');
175188
if (($row = $selection->fetch()) === FALSE) {
176189
throw new Nette\InvalidStateException('Database refetch failed; row does not exist!');

tests/Database/Table/Table.update().phpt

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -68,3 +68,23 @@ $bookTag = $book2->related('book_tag')->insert(array(
6868
$app = $context->table('book')->get(5); // SELECT * FROM `book` WHERE (`id` = ?)
6969
$tags = iterator_to_array($app->related('book_tag')); // SELECT * FROM `book_tag` WHERE (`book_tag`.`book_id` IN (5))
7070
Assert::same('Xbox Game', reset($tags)->tag->name); // SELECT * FROM `tag` WHERE (`tag`.`id` IN (24))
71+
72+
73+
$tag2 = $context->table('tag')->insert(array(
74+
'name' => 'PS4 Game',
75+
)); // INSERT INTO `tag` (`name`) VALUES ('PS4 Game')
76+
77+
$tag2->update(array(
78+
'id' => 1,
79+
)); // UPDATE `tag` SET `id`=1 WHERE (`id` = (?))
80+
Assert::same(1, $tag2->id);
81+
82+
83+
$book_tag = $context->table('book_tag')->get(array(
84+
'book_id' => 5,
85+
'tag_id' => 25,
86+
)); // SELECT * FROM `book_tag` WHERE (`book_id` = (?) AND `tag_id` = (?))
87+
$book_tag->update(new ArrayIterator(array(
88+
'tag_id' => 21,
89+
))); // UPDATE `book_tag` SET `tag_id`=21 WHERE (`book_id` = (?) AND `tag_id` = (?))
90+
Assert::same(21, $book_tag->tag_id);

0 commit comments

Comments
 (0)