首页 > 解决方案 > Codeigniter 3 博客应用程序:每当删除一个类别时,将该类别中所有帖子的 cat_id 设置为 1

问题描述

我正在使用Codeigniter 3.1.8Bootstrap 4开发一个基本的博客应用程序。

有一个帖子和一个类别表。目前,应用程序会在帖子表中插入一个类别 ID,每当创建帖子时(您不能在为其选择类别之前添加帖子),但我没有在两个表之间设置外键关系(为了方便发展) 并且没有级联

在此处输入图像描述

现在我想在两个表之间设置一个特殊的级联关系:每当删除一个类别时,该类别中的所有帖子都应该1cat_id列中。

我已经为应用程序创建了一个安装过程:创建数据库并将其凭据提供给application/config/database.php文件后,您可以运行Install控制器,该控制器将创建所有必要的表:

class Install extends CI_Controller {
    public function __construct()
    {
        parent::__construct();
    }

    public function index(){
        // Create all the database tables if there are none
        // by redirecting to the Migrations controller
        $tables = $this->db->list_tables();
        if (count($tables) == 0) {
            redirect('migrate');
        } else {
            redirect('/');
        }
    }
}

我用来创建帖子表的迁移是:

public function up(){
  $this->dbforge->add_field(array(
  'id'=>array(
    'type'=>'INT',
    'constraint' => 11,
    'unsigned' => TRUE,
    'auto_increment' => TRUE
  ),

  'author_id'=>array(
    'type'=>'INT',
    'constraint' => 11,
    'unsigned' => TRUE,
  ),

  'cat_id'=>array(
    'type'=>'INT',
    'constraint' => 11,
    'unsigned' => TRUE,
  ),

  'title'=>array(
    'type'=>'VARCHAR',
    'constraint' => 255,
  ),

  'slug'=>array(
    'type'=>'VARCHAR',
    'constraint' => 128,
    'unique' => TRUE,
  ),

  'description'=>array(
    'type'=>'VARCHAR',
    'constraint' => 255,
  ),

  'content'=>array(
    'type'=>'TEXT',
  ),

  'post_image'=>array(
    'type'=>'VARCHAR',
    'constraint' => 255,
  ),

 'created_at'=>array(
    'type'=>'TIMESTAMP',
  ),

 'updated_at'=>array(
    'type'=>'TIMESTAMP',
  ),

));

$this->dbforge->add_key('id', TRUE);
$this->dbforge->create_table('posts');
$this->db->query('ALTER TABLE `posts` ADD FOREIGN KEY(`cat_id`) REFERENCES 'categories'(`id`) ON DELETE SET cat_id to 1;');

}

我应该用什么替换最后一行(它具有说明性目的):

$this->db->query('ALTER TABLE `posts` ADD FOREIGN KEY(`cat_id`) REFERENCES 'categories'(`id`) ON DELETE SET cat_id to 1;');

为了得到想要的结果?

更新:我的数据库确实使用InnoDB

标签: phpmysqlcodeignitercodeigniter-3database-migration

解决方案


你需要使用

`ALTER TABLE `posts` ADD FOREIGN KEY(`cat_id`) REFERENCES 'categories'(`id`) ON DELETE SET DEFAULT 1`

但是,请注意,这不适用于InnoDB。 https://dev.mysql.com/doc/refman/5.5/en/innodb-foreign-key-constraints.html


推荐阅读