Home » Php » php – Laravel – Multiple primary key

php – Laravel – Multiple primary key

Posted by: admin July 12, 2020 Leave a comment

Questions:

I’m new on Laravel framework, I try too create table with 2 foreign key and I want they become primary in this table. But I have an error when I write php artisan migrate

SQLSTATE[42000]: Syntax error or access violation: 1068 Multiple primary ke
y defined (SQL: alter table doc_tag add primary key doc_tag_id_tag_primar
y(id_tag)

Schema::create('doc_tag', function(Blueprint $table)
{
    $table->integer('id_doc')->unsigned();
    $table->primary('id_doc');
    $table->foreign('id_doc')
                ->references('id')
                ->on('doc');
    $table->integer('id_tag')->unsigned();
    $table->primary('id_tag');
    $table->foreign('id_tag')
                ->references('id')
                ->on('tag');
});

I know the SQL code which is : (But I do not really know how to translate this SQL code in Laravel)

CREATE TABLE IF NOT EXISTS `Doc_project`.`document_has_Tags` (
  `document_id_document` INT NOT NULL,
  `Tags_id_Tag` INT NOT NULL,
  PRIMARY KEY (`document_id_document`, `Tags_id_Tag`),
  INDEX `fk_document_has_Tags_Tags1_idx` (`Tags_id_Tag` ASC),
  INDEX `fk_document_has_Tags_document1_idx` (`document_id_document` ASC),
  CONSTRAINT `fk_document_has_Tags_document1`
    FOREIGN KEY (`document_id_document`)
    REFERENCES `Doc_project`.`document` (`id_document`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION,
  CONSTRAINT `fk_document_has_Tags_Tags1`
    FOREIGN KEY (`Tags_id_Tag`)
    REFERENCES `Doc_project`.`Tags` (`id_Tag`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION)

It’s an N:N relation

Someone have an idea ?

How to&Answers:

Eloquent doesn’t support multiple primary keys, but if you still want it, send an array to your primary(...).

So in your case:

Schema::create('doc_tag', function(Blueprint $table)
{
    $table->integer('id_doc')->unsigned();
    $table->integer('id_tag')->unsigned();

    $table->primary(['id_tag', 'id_doc']);

    $table->foreign('id_doc')
                ->references('id')
                ->on('doc');    
    $table->foreign('id_tag')
                ->references('id')
                ->on('tag');
});

Answer:

If you want to create primary key on 2 or more columns you should use:

$table->primary(['id_doc','id_tag']);