Home > Net >  Non-Primary, Auto Incrementing Integer in Laravel Migration
Non-Primary, Auto Incrementing Integer in Laravel Migration

Time:11-01

I've scoured the web for this one.

What I'm trying to do:

I have a table that has a primary id. I need to add a column called ex. order_number that automatically increments starting at 1000 and up from there.


The Issue:

PHP doesn't seem to like this, it throws an error

 SQLSTATE[42P16]: Invalid table definition: 7 ERROR:  multiple primary keys for table "orders" are not allowed (SQL: alter table "orders" add column "order_number" serial primary key not null)

My Code:

    public function up()
    {
        Schema::table('orders', function (Blueprint $table) {
            $last_id = Order::orderBy('id', 'desc')->first()->id;
            $table->integer('order_number', true, true)->from($last_id   10001);
        });

        foreach (Order::get() as $order) {
            $order->update([
                'order_number' => 10000   $order->id
            ]);
        }
    }

CodePudding user response:

I think we can make a work around to make it work.

    public function up()
    {
        Schema::table('orders', function (Blueprint $table) {
               $table->id();
               $table->bigIncrements('order_number');

              // if it is making both as primary key
              //drop the primary key constraint from one
              $table->dropPrimary('orders_order_number_primary');
        });
    }

I have not tested it, but I feel it will work, even I feel, if we are using id() for primary key, may be bigIncrements will not get treated as primary key.

Note: You have some customization on possible value for order_number, but I think you can make that workaround in model, but also I am assuming the question is about can we have two auto increment fields in a table.

CodePudding user response:

No Need to use other parameters in

$table->integer('column name')

Use only :-

 public function up()
    {
        Schema::table('orders', function (Blueprint $table) {
            $last_id = Order::orderBy('id', 'desc')->first()->id;
            $table->integer('order_number')->from($last_id   10001);
        });
    }
  • Related