Is there anyway to assign a default value of a table equal to the id itself?

Viewed 517

So I want to set the default value of the column order equal to the id. This is pretty much for sorting purposes.

Is there anyway to do it? Or would there be a better way to achieve the same purpose?

Schema::create('posts', function (Blueprint $table) {
    $table->id();
    $table->string('title');
    $table->bigInteger('order');
    $table->string('path');
    $table->text('description')->default('');

    $table->timestamps();
});
4 Answers

You can't do this with laravel migrations, mysql doesn't support it on table creation.

You could create a mysql trigger to set the field on insert https://dev.mysql.com/doc/refman/8.0/en/trigger-syntax.html

The real question though is why do you want an identical field just for sorting reasons?

Each time after you create/save a new entry in the posts table, just grab the id of the row and save it again:

$post->save();
$post->order = $post->id;
$post->save();

It's not ideal as it requires an additional database operation for every post creation, but in reality it probably won't ever be an issue unless your project gets really big.

No, you can't make this automated.

Even in MySQL 8.0 with expression defaults. See https://dev.mysql.com/doc/refman/8.0/en/data-type-defaults.html which says:

An expression default value cannot depend on a column that has the AUTO_INCREMENT attribute.

You can't write a trigger to do it. You can change column values only in a BEFORE INSERT trigger. But the auto-increment value for your id column has not been generated at that time. The auto-increment value is only available in an AFTER INSERT trigger, but by that time, you can't modify columns of the row, because it has already been inserted.

The only way to do what you want is to INSERT the row, and then subsequently run another SQL UPDATE to copy the auto-increment value from your id column to your order column.

You can do it in the following way. The created event will be called once it is created and will never call on updating

class Post extends Model
{
    protected static function booted() {
        self::created(function (self $post){
            $post->order = $post->id;
            $post->save();
        });
    }
}

Laravel Documentation

Related