我是Laravel框架的新手,我也尝试用2个外键创建表,我希望它们在这个表中成为主要的。但是当我写php artisan migrate
时,我有一个错误 SQLSTATE [42000]:语法错误或访问冲突:1068多个主要ke
y defined(SQL:alter table doc_tag
添加主键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');
});
我知道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)
这是N:N关系
有人有想法吗?
答案 0 :(得分:10)
Eloquent不支持多个主键,但如果您仍然需要,请将数组发送到primary(...)
。
所以在你的情况下:
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');
});
答案 1 :(得分:3)
如果要在2列或更多列上创建主键,则应使用:
$table->primary(['id_doc','id_tag']);