File tree Expand file tree Collapse file tree 3 files changed +85
-0
lines changed
Expand file tree Collapse file tree 3 files changed +85
-0
lines changed Original file line number Diff line number Diff line change @@ -139,4 +139,18 @@ public static function getCustomColumns(): array
139139 'id ' ,
140140 ];
141141 }
142+
143+ /**
144+ * Get a column name for an attribute that can be used in SQL queries.
145+ *
146+ * (`foo` or `data->foo` depending on whether `foo` is in custom columns)
147+ */
148+ public function getColumnForQuery (string $ column ): string
149+ {
150+ if (in_array ($ column , static ::getCustomColumns (), true )) {
151+ return $ column ;
152+ }
153+
154+ return static ::getDataColumn () . '-> ' . $ column ;
155+ }
142156}
Original file line number Diff line number Diff line change @@ -88,6 +88,23 @@ public function model_is_always_decoded_when_accessed_by_user_event()
8888 MyModel::first ();
8989 }
9090
91+ /** @test */
92+ public function column_names_are_generated_correctly ()
93+ {
94+ // FooModel's virtual data column name is 'virtual'
95+ $ virtualColumnName = 'virtual->foo ' ;
96+ $ customColumnName = 'custom1 ' ;
97+
98+ /** @var FooModel $model */
99+ $ model = FooModel::create ([
100+ 'custom1 ' => $ customColumnName ,
101+ 'foo ' => $ virtualColumnName
102+ ]);
103+
104+ $ this ->assertSame ($ customColumnName , $ model ->getColumnForQuery ('custom1 ' ));
105+ $ this ->assertSame ($ virtualColumnName , $ model ->getColumnForQuery ('foo ' ));
106+ }
107+
91108 // maybe add an explicit test that the saving() and updating() listeners don't run twice?
92109 }
93110
@@ -107,3 +124,25 @@ public static function getCustomColumns(): array
107124 ];
108125 }
109126}
127+
128+ class FooModel extends Model
129+ {
130+ use VirtualColumn;
131+
132+ protected $ guarded = [];
133+ public $ timestamps = false ;
134+
135+ public static function getCustomColumns (): array
136+ {
137+ return [
138+ 'id ' ,
139+ 'custom1 ' ,
140+ 'custom2 ' ,
141+ ];
142+ }
143+
144+ public static function getDataColumn (): string
145+ {
146+ return 'virtual ' ;
147+ }
148+ }
Original file line number Diff line number Diff line change 1+ <?php
2+
3+ declare (strict_types=1 );
4+
5+ use Illuminate \Database \Migrations \Migration ;
6+ use Illuminate \Database \Schema \Blueprint ;
7+ use Illuminate \Support \Facades \Schema ;
8+
9+ class CreateFooModelsTable extends Migration
10+ {
11+ /**
12+ * Run the migrations.
13+ *
14+ * @return void
15+ */
16+ public function up ()
17+ {
18+ Schema::create ('foo_models ' , function (Blueprint $ table ) {
19+ $ table ->increments ('id ' );
20+
21+ $ table ->string ('custom1 ' )->nullable ();
22+ $ table ->string ('custom2 ' )->nullable ();
23+
24+ $ table ->json ('virtual ' );
25+ });
26+ }
27+
28+ public function down ()
29+ {
30+ Schema::dropIfExists ('foo_models ' );
31+ }
32+ }
You can’t perform that action at this time.
0 commit comments