diff --git a/src/Abstracts/DataModel.php b/src/Abstracts/DataModel.php index 088fdd0..b409706 100644 --- a/src/Abstracts/DataModel.php +++ b/src/Abstracts/DataModel.php @@ -12,7 +12,7 @@ * @author 10 Quality * @license MIT * @package wp-query-builder - * @version 1.0.7 + * @version 1.0.12 */ abstract class DataModel extends Model { @@ -181,6 +181,37 @@ public function delete() do_action( 'data_model_' . $this->table . '_deleted', $this ); return $deleted; } + /** + * Updates specific columns of the model (not the whole object like save()). + * @since 1.0.12 + * + * @param array $data Data to update. + * + * @return bool + */ + public function update( $data = [] ) + { + // If not data, let save() handle this + if ( empty( $data ) || !is_array( $data ) ) { + return $this->save(); + } + global $wpdb; + $success = false; + $protected = $this->protected_properties(); + if ( $this->{$this->primary_key} ) { + // Update + $success = $wpdb->update( $this->tablename, array_filter( $data, function( $key ) use( $protected ) { + return ! in_array( $key , $protected ); + }, ARRAY_FILTER_USE_KEY ), [$this->primary_key => $this->attributes[$this->primary_key]] ); + if ( $success ) { + foreach ( $data as $key => $value ) { + $this->$key = $value; + } + do_action( 'data_model_' . $this->table . '_updated', $this ); + } + } + return $success; + } /** * Deletes where query. * @since 1.0.0 diff --git a/tests/cases/AbstractModelTest.php b/tests/cases/AbstractModelTest.php index 96ae362..12ac782 100644 --- a/tests/cases/AbstractModelTest.php +++ b/tests/cases/AbstractModelTest.php @@ -8,7 +8,7 @@ * @author 10 Quality * @license MIT * @package wp-query-builder - * @version 1.0.7 + * @version 1.0.12 */ class AbstractModelTest extends TestCase { @@ -169,4 +169,25 @@ public function testSaveTimestamps() $this->assertTrue( $created_at && $created_at->format( $date_format ) === $model->created_at ); $this->assertTrue( $updated_at && $updated_at->format( $date_format ) === $model->updated_at ); } + /** + * Test abstract + * @since 1.0.12 + * @group abstract + * @group model + * @group update + */ + public function testUpdate() + { + // Preapre + global $wpdb; + $model = new Model( [ + 'model_id' => 888999, + 'name' => 'test', + ] ); + // Exec + $flag = $model->update( ['name' => 'updated'] ); + // Assert + $this->assertTrue( $flag ); + $this->assertEquals( 'updated', $model->name ); + } } \ No newline at end of file