diff --git a/tests/VirtualColumnTest.php b/tests/VirtualColumnTest.php index 247b189..6c1d29c 100644 --- a/tests/VirtualColumnTest.php +++ b/tests/VirtualColumnTest.php @@ -105,6 +105,26 @@ public function column_names_are_generated_correctly() $this->assertSame($virtualColumnName, $model->getColumnForQuery('foo')); } + /** @test */ + public function models_extending_a_parent_model_using_virtualcolumn_get_encoded_correctly() + { + // Create a model that extends a parent model using VirtualColumn + // 'foo' is a custom column, 'data' is the virtual column + FooChild::create(['foo' => 'foo']); + $encodedFoo = DB::select('select * from foo_childs limit 1')[0]; + // Assert that the model was encoded correctly + $this->assertNull($encodedFoo->data); + $this->assertSame($encodedFoo->foo, 'foo'); + + // Create another child model of the same parent + // 'bar' is a custom column, 'data' is the virtual column + BarChild::create(['bar' => 'bar']); + $encodedBar = DB::select('select * from bar_childs limit 1')[0]; + + $this->assertNull($encodedBar->data); + $this->assertSame($encodedBar->bar, 'bar'); + } + // maybe add an explicit test that the saving() and updating() listeners don't run twice? } @@ -146,3 +166,37 @@ public static function getDataColumn(): string return 'virtual'; } } + +class ParentModel extends Model +{ + use VirtualColumn; + + public $timestamps = false; + protected $guarded = []; +} + + +class FooChild extends ParentModel +{ + public $table = 'foo_childs'; + + public static function getCustomColumns(): array + { + return [ + 'id', + 'foo', + ]; + } +} +class BarChild extends ParentModel +{ + public $table = 'bar_childs'; + + public static function getCustomColumns(): array + { + return [ + 'id', + 'bar', + ]; + } +} diff --git a/tests/etc/migrations/2023_05_11_000001_create_bar_childs_table.php b/tests/etc/migrations/2023_05_11_000001_create_bar_childs_table.php new file mode 100644 index 0000000..94557d3 --- /dev/null +++ b/tests/etc/migrations/2023_05_11_000001_create_bar_childs_table.php @@ -0,0 +1,31 @@ +increments('id'); + + $table->string('bar')->nullable(); + + $table->json('data')->nullable(); + }); + } + + public function down() + { + Schema::dropIfExists('bar_childs'); + } +} diff --git a/tests/etc/migrations/2023_10_21_000001_create_foo_childs_table.php b/tests/etc/migrations/2023_10_21_000001_create_foo_childs_table.php new file mode 100644 index 0000000..bb39d10 --- /dev/null +++ b/tests/etc/migrations/2023_10_21_000001_create_foo_childs_table.php @@ -0,0 +1,31 @@ +increments('id'); + + $table->string('foo')->nullable(); + + $table->json('data')->nullable(); + }); + } + + public function down() + { + Schema::dropIfExists('foo_childs'); + } +}