Codeigniter 3 博客应用程序:每当删除一个类别时

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

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

http://img.mukewang.com/616048190001a3ae12600322.jpg

现在我想在两个表之间设置一个特殊的级联关系:每当删除一个类别时,该类别中的所有帖子都应该1在该cat_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('/');

        }

    }

}

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

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

为了得到想要的结果?

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


阿波罗的战车
浏览 145回答 3
3回答

鸿蒙传说

这是一个使用php的例子function_delete_category($id) {     $this->db->trans_start();     $this->db->where('cat_id', $id);     $ct = $this->db->count_all_results('posts');     if ($ct > 0) {         $this->db->set('cat_id', 1);         $this->db->where('cat_id', $id);         $this->db->update('posts');     }     $this->db->delete('categories', array('id' => $id));     $this->db->trans_complete();     return $this->db->trans_stats();}
打开App,查看更多内容
随时随地看视频慕课网APP