Skip to content

Commit 1984020

Browse files
committed
#15 Added update() method to models.
1 parent 4955d13 commit 1984020

File tree

2 files changed

+54
-2
lines changed

2 files changed

+54
-2
lines changed

src/Abstracts/DataModel.php

+32-1
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@
1212
* @author 10 Quality <[email protected]>
1313
* @license MIT
1414
* @package wp-query-builder
15-
* @version 1.0.7
15+
* @version 1.0.12
1616
*/
1717
abstract class DataModel extends Model
1818
{
@@ -181,6 +181,37 @@ public function delete()
181181
do_action( 'data_model_' . $this->table . '_deleted', $this );
182182
return $deleted;
183183
}
184+
/**
185+
* Updates specific columns of the model (not the whole object like save()).
186+
* @since 1.0.12
187+
*
188+
* @param array $data Data to update.
189+
*
190+
* @return bool
191+
*/
192+
public function update( $data = [] )
193+
{
194+
// If not data, let save() handle this
195+
if ( empty( $data ) || !is_array( $data ) ) {
196+
return $this->save();
197+
}
198+
global $wpdb;
199+
$success = false;
200+
$protected = $this->protected_properties();
201+
if ( $this->{$this->primary_key} ) {
202+
// Update
203+
$success = $wpdb->update( $this->tablename, array_filter( $data, function( $key ) use( $protected ) {
204+
return ! in_array( $key , $protected );
205+
}, ARRAY_FILTER_USE_KEY ), [$this->primary_key => $this->attributes[$this->primary_key]] );
206+
if ( $success ) {
207+
foreach ( $data as $key => $value ) {
208+
$this->$key = $value;
209+
}
210+
do_action( 'data_model_' . $this->table . '_updated', $this );
211+
}
212+
}
213+
return $success;
214+
}
184215
/**
185216
* Deletes where query.
186217
* @since 1.0.0

tests/cases/AbstractModelTest.php

+22-1
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@
88
* @author 10 Quality <[email protected]>
99
* @license MIT
1010
* @package wp-query-builder
11-
* @version 1.0.7
11+
* @version 1.0.12
1212
*/
1313
class AbstractModelTest extends TestCase
1414
{
@@ -169,4 +169,25 @@ public function testSaveTimestamps()
169169
$this->assertTrue( $created_at && $created_at->format( $date_format ) === $model->created_at );
170170
$this->assertTrue( $updated_at && $updated_at->format( $date_format ) === $model->updated_at );
171171
}
172+
/**
173+
* Test abstract
174+
* @since 1.0.12
175+
* @group abstract
176+
* @group model
177+
* @group update
178+
*/
179+
public function testUpdate()
180+
{
181+
// Preapre
182+
global $wpdb;
183+
$model = new Model( [
184+
'model_id' => 888999,
185+
'name' => 'test',
186+
] );
187+
// Exec
188+
$flag = $model->update( ['name' => 'updated'] );
189+
// Assert
190+
$this->assertTrue( $flag );
191+
$this->assertEquals( 'updated', $model->name );
192+
}
172193
}

0 commit comments

Comments
 (0)