如何使用Yii2中的Migration创建复合主键?

use*_*234 16 sql database-migration yii2

我试图运行yii migrate,但它显示以下错误:

create table news-cate ...Exception: SQLSTATE[42000]: Syntax error or access violation: 1075 Incorrect table definition; there can be only one auto column and it must be defined as a key
The SQL being executed was: CREATE TABLE `news-cate` (
        `news-id` int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY,
        `cate-id` int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY
Run Code Online (Sandbox Code Playgroud)

这是我的代码:

class m150821_083020_create_newscate_table extends Migration
{
    public function safeUp()
    {
        $this->createTable('news-cate', [
            'news-id' => $this->primaryKey(),
            'cate-id' => $this->primaryKey(),
        ]);
        $this->addForeignKey("fk_news_cate_nid", "news-cate", "news-id", "news", "id", "RESTRICT", "CASCADE");
        $this->addForeignKey("fk_news_cate_cid", "news-cate", "cate-id", "category", "id", "RESTRICT", "CASCADE");
    }

    public function safeDown()
    {
        echo "m150821_083020_create_newscate_table cannot be reverted.\n";
        $this->dropTable("news-cate");
        return false;
    }
}
Run Code Online (Sandbox Code Playgroud)

那么如何使用Yii2中的Migration创建复合主键?

aro*_*hev 23

UPDATE

从yii版本2.06开始,您可以使用新的模式构建器:

<?php
use yii\db\Migration;
...
$this->createTable('news-cate', [
    'news-id' => $this->integer()->notNull(),
    'cate-id' => $this->integer()->notNull(),
]);
$this->addPrimaryKey('news-cate_pk', 'news-cate', ['news-id', 'cate-id']);
...
?>
Run Code Online (Sandbox Code Playgroud)

原始答案

不要在表创建中添加主键,只声明类型:

use yii\db\Schema;

,,,

$this->createTable('news-cate', [
    'news-id' => Schema::TYPE_INTEGER . ' NOT NULL',
    'cate-id' => Schema::TYPE_INTEGER . ' NOT NULL',
]);
Run Code Online (Sandbox Code Playgroud)

之后,您可以像这样添加复合主键:

$this->addPrimaryKey('news-cate_pk', 'news-cate', ['news-id', 'cate-id']);
Run Code Online (Sandbox Code Playgroud)

对于多列,addPrimaryKey()方法中允许使用数组.

这比编写原始sql要好.

  • 这也是创建非整数类型主键的最佳方式。 (2认同)

sca*_*dge 7

试试这种方式

public function safeUp()
{
   $this->createTable('news-cate', [
        'news-id' =>'int NOT NULL',
        'cate-id' =>'int NOT NULL',
        'PRIMARY KEY (news-id,cate-id)'
      ]);
    $this->addForeignKey("fk_news_cate_nid", "news-cate", "news-id", "news", "id", "RESTRICT", "CASCADE");
    $this->addForeignKey("fk_news_cate_cid", "news-cate", "cate-id", "category", "id", "RESTRICT", "CASCADE");
}
Run Code Online (Sandbox Code Playgroud)