Home > Blockchain >  Need to define 02 primary keys in here
Need to define 02 primary keys in here

Time:02-15

I want to define 02 primary keys in this migration , also i need to define it in model class. i m using laravel 9 version . When i define this . it gives following error.

Schema::create('salaries', function (Blueprint $table) {
            $table->increments('id')->primary();
            $table->unsignedInteger('emp_no')->primary();
            $table->foreign('emp_no')->references('id')->on('employees')->cascadeOnDelete()->cascadeOnUpdate();
            $table->integer('salary');
            $table->date('from_date')->primary();
            $table->date('to_date');
            $table->timestamps();
        });

Output

 SQLSTATE[42000]: Syntax error or access violation: 1068 Multiple primary key defined (SQL
: alter table `titles` add primary key `titles_id_primary`(`id`))

CodePudding user response:

Try this way, here is my e.g:

Schema::create("kitchen", function($table) {
    $table->increments('id');
    $table->integer('restaurant_id');
    $table->string('name');
    $table->unique(['restaurant_id', 'name']);
});

CodePudding user response:

try this for a composite primary key

Schema::create('salaries', function (Blueprint $table) {
            $table->increments('id');
            $table->unsignedInteger('emp_no');
            $table->foreign('emp_no')->references('id')->on('employees')->cascadeOnDelete()->cascadeOnUpdate();
            $table->integer('salary');
            $table->date('from_date');
            $table->date('to_date');
            $table->timestamps();
            $table->primary(['id','emp_no','from_date']);
        });

Or you can make necessary fields unique if it works for you

  • Related