Laravel - 多个主键
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26344948/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Laravel - Multiple primary key
提问by Alexis
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
我是 Laravel 框架的新手,我也尝试使用 2 个外键创建表,并且我希望它们成为该表中的主要表。但是我写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
)
SQLSTATE[42000]:语法错误或访问冲突:1068
定义了多个doc_tag
主键(SQL:alter table 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)
我知道 SQL 代码是:(但我真的不知道如何在 Laravel 中翻译此 SQL 代码)
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
这是 N:N 关系
Someone have an idea ?
有人有想法吗?
回答by Marwelln
Eloquent doesn't support multiple primary keys, but if you still want it, send an array to your primary(...)
.
Eloquent 不支持多个主键,但如果您仍然需要它,请将一个数组发送到您的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');
});
回答by Marcin Nabia?ek
If you want to create primary key on 2 or more columns you should use:
如果要在 2 个或更多列上创建主键,则应使用:
$table->primary(['id_doc','id_tag']);