I am trying to create a database table using controller method. Each time I run my code, I get the following Error Message. I am using Yii2 Framework
SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint The SQL being executed was: CREATE TABLE
auth_item
(name
varchar(64) not null,type
int not null,description
text,rule_name
varchar(64),data
text,created_at
int not null,updated_at
int not null ) CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE=InnoDB Error Info: Array ( [0] => HY000 [1] => 1215 [2] => Cannot add foreign key constraint )Caused by: PDOException
SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint
in /home/offneo/Projects/MODULEMANAGER/Product/Software/vendor/yiisoft/yii2/db/Command.php at line 844
Here is my code in controller method actionInstall
$db = Yii::$app->db;
$tableOptions = null;
$status = true;
if ($db->driverName === 'mysql') {
// http://stackoverflow.com/questions/766809/whats-the-difference-between-utf8-general-ci-and-utf8-unicode-ci
$tableOptions = 'CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE=InnoDB';
}
// Table auth_rule
if ( $db->getTableSchema('auth_rule') === null ) {
$status &= (bool) $db->createCommand()->createTable('auth_rule', [
'name' => 'varchar(64) not null',
'data' => "text",
'created_at' => "int",
'updated_at' => "int",
'PRIMARY KEY (name)'
], $tableOptions)->execute();
$status &= (bool) $db->createCommand()->createIndex('name_UNIQUE', 'auth_rule', 'name', true)->execute();
}
// Table auth_item
if ( $db->getTableSchema('auth_item') === null ) {
$status &= (bool) $db->createCommand()->createTable('auth_item', [
'name' => 'varchar(64) not null',
'type'=>'int not null',
'description' => 'text',
'rule_name' => "varchar(64)",
'data'=>'text',
'created_at' => 'int not null',
'updated_at' => 'int not null'
], $tableOptions)->execute();
$status &= (bool) $db->createCommand()->addPrimaryKey('name_pk', 'auth_item', 'name')->execute();
// $status &= (bool) $db->createCommand()->addForeignKey('fk_auth_item_auth_rule1_idx', 'auth_item', 'rule_name', 'auth_rule', 'name', 'SET NULL', 'CASCADE')->execute();
// $status &= (bool) $db->createCommand()->createIndex('fk_auth_item_auth_rule1_idx', 'auth_item', 'name', false)->execute();
}