在codeigniter迁移中创建外键失败

时间:2017-12-01 12:07:59

标签: php mysql codeigniter

尝试通过

在codeigniter迁移中添加外键

我有两张桌子

tbl_doc_types
   id
   name

tbl_docs
  id
  doc_type //foreign key to tbl_doc_types

所以在我的迁移中

class Migration_Add_Tbl_Legal_Documents extends CI_Migration
 {

  public function up()
   {
    $this->dbforge->add_field(array(

         'doc_type' => array(
            'type' => 'INT',
        ),

     $this->dbforge->add_field('CONSTRAINT FOREIGN KEY (doc_type) REFERENCES tbl_doc_types(id)');

但是现在出现错误

Foreign key constraint is incorrectly formed")

我哪里错了?

1 个答案:

答案 0 :(得分:2)

尝试使用类似

的内容
$this->db->query('ALTER TABLE `table` ADD CONSTRAINT `name_contraint` FOREIGN KEY(`id_table`) REFERENCES table2(`id_table2`) ON DELETE RESTRICT ON UPDATE RESTRICT;');

而不是$ this-> dbforge-> add_field