为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

PHP
阿波罗的战车 2021-10-08 21:30:43
我正在使用Codeigniter 3.1.8和Bootstrap 4开发一个基本的博客应用程序。有一个帖子和一个类别表。目前,应用程序会在创建帖子时将类别 ID插入到帖子表中(您不能在为其选择类别之前添加帖子),但是我没有在两个表之间设置外键关系(为了方便的发展)并且没有级联。现在我想在两个表之间设置一个特殊的级联关系:每当删除一个类别时,该类别中的所有帖子都应该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。
查看完整描述

3 回答

?
鸿蒙传说

TA贡献1865条经验 获得超7个赞

这是一个使用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();


}


查看完整回答
反对 回复 2021-10-08
  • 3 回答
  • 0 关注
  • 144 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信