0

I am doing a test, but not sure how to do it with laravel migration file. In short, there is the auto incrementing id field (which will always be a positive integer). But I also want a negative_id field, which would be the value of id * -1, and would be automatically inserted in sync when an id is inserted to the database. So when the first user is added, id is automatically added as 1 so negative_id should be added as -1 for that row, since 1 * -1 = -1. The table should look like this:

| id | negative_id 
------------------
| 1  | -1                   
| 2  | -2                   
| 3  | -3  

Below is my current migration file:

<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateUsersTable extends Migration {
    public function up(){
        Schema::create('users', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('negative_id'); // how to make this id*-1 value
        });
    }

    public function down(){
        Schema::dropIfExists('users');
    }

Any idea how to accomplish this from the migration file?

Wonka
  • 8,244
  • 21
  • 73
  • 121
  • I think, you can try triggers.(if we talk about the database level). On the other hand, you can use `Eloquent` events [docs](https://laravel.com/docs/5.5/eloquent#events) – Pavel Apr 26 '18 at 19:27

1 Answers1

0

You may want to look at Generated columns

$table->integer('negative_id')->virtualAs('id*-1');

Look at this link for more info.

Ralph519
  • 85
  • 2
  • 11
  • Hmmm... When I add that to migration and migrate I get `SQLSTATE[HY000]: General error: 3109 Generated column 'negative_id' cannot refer to auto-increment column.` – Wonka Apr 27 '18 at 16:49