1
0
Fork 0
mirror of https://github.com/archtechx/virtualcolumn.git synced 2025-12-12 09:24:02 +00:00

feat: Add new column for "foo_child" table to link with the table "foo".

- Add to Virtual Column a new rule to prevent store relationships names in the "data" column.
This commit is contained in:
Henrique Felix 2025-05-12 17:23:27 +00:00
parent 75718edcfe
commit dda54ddab0
3 changed files with 44 additions and 0 deletions

View file

@ -76,6 +76,15 @@ trait VirtualColumn
// Remove attribute from the model
unset($this->attributes[$key]);
unset($this->original[$key]);
// Check if the attribute is a method on the model
$myKeyIsAnFunction = method_exists($this, $key);
// If the attribute is a method, remove it from the attributes array
// This is to prevent the attribute from being added to the data column
if ($myKeyIsAnFunction) {
unset($attributes[$key]);
}
}
// Add attribute to the data column

View file

@ -8,6 +8,7 @@ use Illuminate\Support\Facades\Crypt;
use Illuminate\Database\Eloquent\Model;
use Stancl\VirtualColumn\VirtualColumn;
use Illuminate\Contracts\Database\Eloquent\CastsAttributes;
use Illuminate\Database\Eloquent\Relations\HasMany;
class VirtualColumnTest extends TestCase
{
@ -162,6 +163,32 @@ class VirtualColumnTest extends TestCase
// Reset static property
MyModel::$customEncryptedCastables = [];
}
/** @test */
public function test_try_save_property_same_name_as_function() {
/** @var FooModel $model */
$model = FooModel::create([
'custom1' => "bar",
'custom2' => 'ool',
'childrens' => [ // children are the name of the relation with FooChild
'custom' => 'abc'
]
]);
// After save, we should ignore the relationship as parameter
// To not throw an exception when trying to access the relation.
$this->assertTrue($model->childrens instanceof \Illuminate\Database\Eloquent\Collection);
$this->assertTrue($model->childrens() instanceof \Illuminate\Database\Eloquent\Relations\HasMany);
$model->childrens()->create([
'foo' => 'test'
]);
// Double check after add a real foo child.
// Check if we dont get the error to call a eloquent method in array.
$this->assertTrue($model->childrens()->first() instanceof FooChild);
}
}
class ParentModel extends Model
@ -200,6 +227,11 @@ class FooModel extends ParentModel
{
return 'virtual';
}
public function childrens(): HasMany
{
return $this->hasMany(FooChild::class, 'foo_id');
}
}
class EncryptedCast implements CastsAttributes
@ -223,6 +255,7 @@ class FooChild extends ParentModel
{
return [
'id',
'foo_id',
'foo',
];
}

View file

@ -18,6 +18,8 @@ class CreateFooChildsTable extends Migration
Schema::create('foo_childs', function (Blueprint $table) {
$table->increments('id');
$table->unsignedInteger('foo_id')->nullable();
$table->string('foo')->nullable();
$table->json('data')->nullable();