@watheq I’d just be using accessors for full name and status values in your model, rather than storing them as virtual columns like that.
Aug 20, 2024
6
Level 14
Postgres `generatedAs` and `storedAs` in Laravel migaration
I have this migration. I am using Postgres, I found that generatedAs and storedAs are supported by Postgres.. I am a beginner in Postgres.
Schema::create('users', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('first_name');
$table->string('last_name');
$table->string('full_name')->generatedAs("first_name || ' ' || last_name"); // error
$table->boolean('active')->default(false);
$table->string('status')->storedAs("CASE WHEN active = 1 THEN 'Active' ELSE 'Inactive' END"); // error
});
The error is
Illuminate\Database\QueryException
SQLSTATE[42601]: Syntax error: 7 ERROR: syntax error at or near "first_name"
LINE 1: ...r(255) not null generated by default as identity (first_name...
^ (Connection: pgsql, SQL: create table "users" ("id" bigserial not null primary key, "first_name" varchar(255) not null, "last_name" varchar(255) not null, "full_name" varchar(255) not null generated by default as identity (first_name || ' ' || last_name), "active" boolean not null default '0', "status" varchar(255) not null generated always as (CASE WHEN active = 1 THEN 'Active' ELSE 'Inactive' END) stored))
Level 104
@Watheq I believe what you want actually is the storedAs method only; the full_name column is not an identity column where the Expression should be a Sequence:
->generatedAs($expression)Create an identity column with specified sequence options (PostgreSQL).
Instead, using storedAs, you will get the expected calculated value from the existing columns
$table->string('full_name')->storedAs("first_name || ' ' || last_name");
1 like
Please or to participate in this conversation.