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

前端之家收集整理的这篇文章主要介绍了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更好.

原文链接:https://www.f2er.com/mssql/81398.html

猜你在找的MsSQL相关文章