加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > MsSql教程 > 正文

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

发布时间:2020-12-12 16:47:30 所属栏目:MsSql教程 来源:网络整理
导读:我试图运行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 keyThe SQL being exe
我试图运行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 yiidbSchema;,$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更好.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读