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

Merge pull request #9 from lukinovec/generate-column-name

Add method for generating the column name
This commit is contained in:
Samuel Štancl 2022-10-21 14:09:30 +02:00 committed by GitHub
commit ab3f943990
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
3 changed files with 85 additions and 0 deletions

View file

@ -139,4 +139,18 @@ trait VirtualColumn
'id',
];
}
/**
* Get a column name for an attribute that can be used in SQL queries.
*
* (`foo` or `data->foo` depending on whether `foo` is in custom columns)
*/
public function getColumnForQuery(string $column): string
{
if (in_array($column, static::getCustomColumns(), true)) {
return $column;
}
return static::getDataColumn() . '->' . $column;
}
}

View file

@ -88,6 +88,23 @@ class VirtualColumnTest extends TestCase
MyModel::first();
}
/** @test */
public function column_names_are_generated_correctly()
{
// FooModel's virtual data column name is 'virtual'
$virtualColumnName = 'virtual->foo';
$customColumnName = 'custom1';
/** @var FooModel $model */
$model = FooModel::create([
'custom1' => $customColumnName,
'foo' => $virtualColumnName
]);
$this->assertSame($customColumnName, $model->getColumnForQuery('custom1'));
$this->assertSame($virtualColumnName, $model->getColumnForQuery('foo'));
}
// maybe add an explicit test that the saving() and updating() listeners don't run twice?
}
@ -107,3 +124,25 @@ class MyModel extends Model
];
}
}
class FooModel extends Model
{
use VirtualColumn;
protected $guarded = [];
public $timestamps = false;
public static function getCustomColumns(): array
{
return [
'id',
'custom1',
'custom2',
];
}
public static function getDataColumn(): string
{
return 'virtual';
}
}

View file

@ -0,0 +1,32 @@
<?php
declare(strict_types=1);
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateFooModelsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('foo_models', function (Blueprint $table) {
$table->increments('id');
$table->string('custom1')->nullable();
$table->string('custom2')->nullable();
$table->json('virtual');
});
}
public function down()
{
Schema::dropIfExists('foo_models');
}
}