File tree Expand file tree Collapse file tree 2 files changed +65
-1
lines changed
Expand file tree Collapse file tree 2 files changed +65
-1
lines changed Original file line number Diff line number Diff line change @@ -706,6 +706,30 @@ public function is_relation_loaded( $attribute ) {
706706 return array_key_exists ( $ attribute , $ this ->_relations );
707707 }
708708
709+ /**
710+ * Refresh the attributes on this model.
711+ *
712+ * This will fetch the latest data from either the cache or DB.
713+ *
714+ * @param bool $destroy_changes If true, will destroy local changes.
715+ *
716+ * @since 2.0.0
717+ */
718+ public function refresh ( $ destroy_changes = false ) {
719+
720+ if ( ! $ this ->exists () ) {
721+ return ;
722+ }
723+
724+ $ data = (array ) static ::get_data_from_pk ( $ this ->get_pk () );
725+
726+ $ this ->_original = $ data ;
727+
728+ if ( $ destroy_changes ) {
729+ $ this ->set_raw_attributes ( $ data );
730+ }
731+ }
732+
709733 /**
710734 * Sync the model's original attributes with its current state.
711735 *
@@ -736,7 +760,6 @@ public function sync_original_attribute( $attribute ) {
736760 return $ this ;
737761 }
738762
739-
740763 /**
741764 * Determine if the model as a whole or given attribute(s) have been modified.
742765 *
Original file line number Diff line number Diff line change @@ -407,4 +407,45 @@ public function test_create_many_multiple_queries() {
407407 remove_filter ( 'ironbound_db_perform_insert_many_as_single_query ' , '__return_false ' );
408408 }
409409
410+ public function test_refresh () {
411+ $ model = ModelWithForeignPost::create ( array (
412+ 'price ' => 24.75
413+ ) );
414+ $ model ->price = 50.00 ;
415+
416+ $ _model = ModelWithForeignPost::get ( $ model ->get_pk () );
417+ $ _model ->price = 45.00 ;
418+ $ _model ->save ();
419+
420+ $ this ->assertEquals ( 50.00 , $ model ->price );
421+ $ this ->assertTrue ( $ model ->is_dirty () );
422+
423+ $ model ->refresh ();
424+
425+ $ this ->assertEquals ( 50.00 , $ model ->price );
426+ $ this ->assertTrue ( $ model ->is_dirty () );
427+
428+ $ model ->price = 45 ;
429+ $ this ->assertEquals ( 45.00 , $ model ->price );
430+ $ this ->assertFalse ( $ model ->is_dirty () );
431+ }
432+
433+ public function test_refresh_and_destroy_local_changes () {
434+ $ model = ModelWithForeignPost::create ( array (
435+ 'price ' => 24.75
436+ ) );
437+ $ model ->price = 50.00 ;
438+
439+ $ _model = ModelWithForeignPost::get ( $ model ->get_pk () );
440+ $ _model ->price = 45.00 ;
441+ $ _model ->save ();
442+
443+ $ this ->assertEquals ( 50.00 , $ model ->price );
444+ $ this ->assertTrue ( $ model ->is_dirty () );
445+
446+ $ model ->refresh ( true );
447+
448+ $ this ->assertEquals ( 45.00 , $ model ->price );
449+ $ this ->assertFalse ( $ model ->is_dirty () );
450+ }
410451}
You can’t perform that action at this time.
0 commit comments