首页 > 解决方案 > Codeigniter 3 迁移:在第一次迁移运行时添加未分类的帖子类别

问题描述

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

我使用迁移文件(001_create_authors.php最多005_create_comments.php)来自动创建必要的数据库表。

除了创建categories表格之外,我还需要在其中插入默认的“未分类”类别,因为帖子必须属于一个类别。

在此处输入图像描述

迁移的当前代码:

class Migration_Create_Categories extends CI_Migration
{

  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,
      ),

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

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

    ));
    $this->dbforge->add_key('id', TRUE);
    $this->dbforge->create_table('categories');
  }

  public function down()
  {
    $this->dbforge->drop_table('categories');
  }

}

为了在第一次迁移运行时在类别表中插入默认的“未分类”类别,我必须在上面的代码中添加什么?

标签: phpcodeignitercodeigniter-3

解决方案


$this->dbforge->create_table('categories');
//after this line
$data = array(
            //'id'         => leave this as it will auto created
            'author_id'    => 1,
            'name'         => 'Uncategorized'
            //'created_at' => leave it as this will auto created 
);

$this->db->insert('categories', $data);

推荐阅读