如果数据库为空,如何运行Codeigniter迁移

我正在将我的Codeigniter 3.1.4开发环境移动到Docker容器中。 当第一次运行docker镜像时,如果数据库为空,我希望Codeigniter自动在数据库中创建表,而不是我必须导出当前的开发数据库,​​然后将其导入到Mysql docker中。 </ p>

我在开发期间(通过命令行)已经使用迁移库来更改数据库模式。 听起来我觉得迁移库对于这个任务来说是完美的,但我想不出我应该从哪里调用它。 例如。 - 我是否在database.php的末尾添加了一些代码来检查数据库是否存在,然后以某种方式调用我的迁移控制器? </ p>
</ div>

展开原文

原文

I'm moving my Codeigniter 3.1.4 development environment into a Docker container at the moment. When running a docker image for the first time, I would like Codeigniter to automatically create tables in the database if the database is empty rather than me having to export my current development database and then import it into the Mysql docker.

I already use the migration library during development (via the command-line) to make changes to the database schema. It sounds to me like the migration library would be perfect for this task, but I can't think of where I should call it from. E.g. - do I add some code to the end of database.php to check if the database exists and then call my migration controller somehow?

1个回答

I found one way to accomplish this. In MY_Controller class, which is a class that extends CI_Controller, I check the database to see if the table ci_sessions exists. If not, I make the assumption that the database is empty and I should run the migration. Here is an example:

class MY_Controller extends CI_Controller {

    function __construct() {
        parent::__construct();

        // If ci_sessions doesn't exist, run db migration (via command-line)
        if (!$this->db->table_exists('ci_sessions')) {
            $output = shell_exec("php index.php migrate");
            if (strncmp($output, "Migration worked!", 17) != 0) {
                exit($output);
            }
        }

        $this->load->library ( 'session' );
        $this->load->model ( 'user_model' );

    }
}

Notice that I'm running the migration via a shell command. This is in order to prevent URL access to the migration controller. There might be a neater way of doing this but I haven't figured out how yet.

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问