无法在MySQL数据库中添加外键

时间:2018-11-04 22:02:26

标签: php mysql yii2 migration

我试图通过发布表中的user_id和用户表中的id来使发布表与用户之间一对一的关系。

 /**
         * @inheritdoc
         */
        public function up()
        {
            $this->createTable('user', [
                'id' => $this->integer()->primaryKey(),
                'name'=>$this->string(),
                'email'=>$this->string()->defaultValue(null),
                'password'=>$this->string(),
                'isAdmin'=>$this->integer()->defaultValue(0),
                'photo'=>$this->string()->defaultValue(null)
            ]);


        }

        /**
         * @inheritdoc
         */
        public function down()
        {
            $this->dropTable('user');
        }

 public function up()
    {
        $this->createTable('post', [
            'id' => $this->primaryKey(),
            'title'=>$this->string(),
            //'description'=>$this->text(),
            'content'=>$this->text(),
            'date'=>$this->date(),
          //  'image'=>$this->string(),
            'viewed'=>$this->integer(),
            'user_id'=>$this->integer(),
            'status'=>$this->integer(),
            'category_id'=>$this->integer(),
        ]);

        $this->createIndex(
            'idx-post-user_id',
            'post',
            'user_id'
        );

        // add foreign key for table `user`
        $this->addForeignKey(
            'fk-post-user_id',
            'post',
            'user_id',
            'user',
            'id',
            'CASCADE'
        );


    }

    /**
     * @inheritdoc
     */
    public function down()
    {
        $this->dropTable('article');
    }

但是我出错了

add foreign key fk-post-user_id: post (user_id) references user (id)
...Exception 'yii\db\Exception' with message 'SQLSTATE[HY000]: General
error: 1215 Cannot add foreign key constraint The SQL being executed
was: ALTER TABLE `post` ADD CONSTRAINT `fk-post-user_id` FOREIGN KEY
(`user_id`) REFERENCES `user` (`id`) ON DELETE CASCADE'

如何建立这种关系?

1 个答案:

答案 0 :(得分:0)

尝试使用'user_id' => $this->integer()->notNull(),