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 ?
A primary key is a field or set of fields with values that are unique throughout a table. Values of the key can be used to refer to entire records, because each record has a different value for the key. Each table can only have one primary key.
A table cannot have more than one primary key. A primary key's main features are: It must contain a unique value for each row of data. It cannot contain null values.
A composite key in SQL can be defined as a combination of multiple columns, and these columns are used to identify all the rows that are involved uniquely. Even though a single column can't identify any row uniquely, a combination of over one column can uniquely identify any record.
By default, Eloquent models expect for the primary key to be named 'id' . If that is not your case, you can change the name of your primary key by specifying the $primaryKey property.
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');
});
If you want to create primary key on 2 or more columns you should use:
$table->primary(['id_doc','id_tag']);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With