sql – 如何使用Yii2中的迁移创建复合主键?

我试图运行yii迁移,但它显示以下错误
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

这是我的代码

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","cate-id","category","CASCADE");
    }

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

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

解决方法

在表创建中不要添加主键,只能声明类型:
use yii\db\Schema;,$this->createTable('news-cate',[
    'news-id' => Schema::TYPE_INTEGER . ' NOT NULL','cate-id' => Schema::TYPE_INTEGER . ' NOT NULL',]);

之后,您可以添加如下复合主键:

$this->addPrimaryKey('news-cate_pk','news-cate',['news-id','cate-id']);

对于多列,阵列允许在addPrimaryKey()方法中.

这比编写原始的sql更好.

相关文章

SELECT a.*,b.dp_name,c.pa_name,fm_name=(CASE WHEN a.fm_n...
if not exists(select name from syscolumns where name=&am...
select a.*,pano=a.pa_no,b.pa_name,f.dp_name,e.fw_state_n...
要在 SQL Server 2019 中设置定时自动重启,可以使用 Window...
您收到的错误消息表明数据库 'EastRiver' 的...
首先我需要查询出需要使用SQL Server Profiler跟踪的数据库标...