mirror of
https://github.com/codeigniter4/CodeIgniter4.git
synced 2025-02-20 11:44:28 +08:00
Update method in database accepts multiple primary keys now. Fixes #865
This commit is contained in:
parent
333617e3ee
commit
12a5f0d2c8
@ -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
|
||||
|
@ -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']);
|
||||
}
|
||||
}
|
||||
|
@ -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
|
||||
|
Loading…
x
Reference in New Issue
Block a user