Skip to content

Commit

Permalink
Merge pull request #9 from lukinovec/generate-column-name
Browse files Browse the repository at this point in the history
Add method for generating the column name
  • Loading branch information
stancl committed Oct 21, 2022
2 parents 66458d0 + ac0dccc commit ab3f943
Show file tree
Hide file tree
Showing 3 changed files with 85 additions and 0 deletions.
14 changes: 14 additions & 0 deletions src/VirtualColumn.php
Original file line number Diff line number Diff line change
Expand Up @@ -139,4 +139,18 @@ public static function getCustomColumns(): array
'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;
}
}
39 changes: 39 additions & 0 deletions tests/VirtualColumnTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,23 @@ public function model_is_always_decoded_when_accessed_by_user_event()
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?
}

Expand All @@ -107,3 +124,25 @@ public static function getCustomColumns(): array
];
}
}

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';
}
}
32 changes: 32 additions & 0 deletions tests/etc/migrations/2022_10_21_000001_create_foo_models_table.php
Original file line number Diff line number Diff line change
@@ -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');
}
}

0 comments on commit ab3f943

Please sign in to comment.