Update method in database accepts multiple primary keys now. Fixes #865

This commit is contained in:
Lonnie Ezell 2018-07-15 23:17:59 -05:00
parent 333617e3ee
commit 12a5f0d2c8
No known key found for this signature in database
GPG Key ID: 8EB408F8D82F5002
3 changed files with 40 additions and 1 deletions

View File

@ -635,6 +635,11 @@ class Model
{
$escape = null;
if (is_numeric($id))
{
$id = [$id];
}
if (empty($data))
{
$data = $this->tempData['data'] ?? null;
@ -692,7 +697,7 @@ class Model
if ($id)
{
$builder = $builder->where($this->table.'.'.$this->primaryKey, $id);
$builder = $builder->whereIn($this->table.'.'.$this->primaryKey, $id);
}
// Must use the set() method to ensure objects get converted to arrays

View File

@ -615,4 +615,22 @@ class ModelTest extends CIDatabaseTestCase
'name' => 'Fred Flintstone'
]);
}
public function testUpdateArray()
{
$model = new EventModel();
$data = [
'name' => 'Foo',
'email' => 'foo@example.com',
'country' => 'US',
'deleted' => 0
];
$id = $model->insert($data);
$model->update([1,2], ['name' => 'Foo Bar']);
$this->seeInDatabase('user', ['id' => 1, 'name' => 'Foo Bar']);
$this->seeInDatabase('user', ['id' => 2, 'name' => 'Foo Bar']);
}
}

View File

@ -273,6 +273,22 @@ of the columns in $table, while the array's values are the values to save for th
$userModel->update($id, $data);
Multiple records may be updated with a single call by passing an array of primary keys as the first parameter::
$data = [
'active' => 1
];
$userModel->update([1, 2, 3], $data);
When you need a more flexible solution, you can leaven the parameters empty and it functions like the Query Builder's
update command, with the added benefit of validation, events, etc::
$userModel
->whereIn('id', [1,2,3])
->set(['active' => 1]
->update();
**save()**
This is a wrapper around the insert() and update() methods that handles inserting or updating the record