php - 使用 codeigniter 的迁移类创建数据库
问题描述
我想将 Codeigniter 的迁移类集成到我的项目的构建过程中。我可以使用迁移类来创建数据库,还是只是为了更新数据库结构?
我的迁移类如下所示:
class Migration_base extends CI_Migration {
public function up()
{
$this->dbforge->create_database('my_db');
}
public function down()
{
$this->dbforge->drop_database('my_db');
}
}
当我运行此代码时:
class Migrate extends CI_Controller
{
public function index()
{
$this->load->library('migration');
if ($this->migration->current() === FALSE)
{
show_error($this->migration->error_string());
}
}
}
我收到这条消息:
Database error: A Database Error Occurred
Unable to connect to your database server using the provided settings.
Filename: path_to_codeigniter/codeigniter/framework/system/database/DB_driver.php
Line Number: 436
在我可以使用迁移类之前,似乎数据库必须已经存在。我是否正确并且需要在我首先创建数据库的迁移类周围编写一个包装器?
解决方案
您怀疑需要一种解决方法才能在迁移过程中创建数据库,这似乎是正确的。我不知道它是否可以被称为错误或缺少的功能,但它不会像写的那样做。
最大的问题是_migration_table
该类创建的需要在被迁移的数据库中。一个经典的“鸡或蛋”问题。
文档假设但未解决的另一个可能问题是要迁移的数据库是应该“加载”的数据库。
我认为您的控制器的以下版本Migrate
将处理这两个问题。
class Migrate extends CI_Controller
{
public function index()
{
if( ! isset($this->db))
{
throw new RuntimeException("Must have a database loaded to run a migration");
}
// Are we connected to 'my_db' ?
if( ! $this->db->database !== 'my_db')
{
//find out if that db even exists
$this->load->dbutil();
if( ! $this->dbutil->database_exists('my_db'))
{
// try to create 'my_db'
$this->load->dbforge();
if( ! $this->dbforge->create_database('my_db'))
{
throw new RuntimeException("Could not create the database 'my_db");
}
}
// Connection data for 'my_db' must be available
// in /config/database.php for this to work.
if(($db = $this->load->database('my_db', TRUE)) === TRUE)
{
$this->db = $db; //replace the previously loaded database
}
else
{
throw new RuntimeException("Could not load 'my_db' database");
}
}
$this->load->library('migration');
if($this->migration->current() === FALSE)
{
show_error($this->migration->error_string());
}
}
}
请知道我没有测试过这段代码。可能存在语法、逻辑或其他错误。如果不出意外,希望它能为您提供一个良好的起点
推荐阅读
- python-3.x - 如何使用 Pandas 在数据框中生成缺失的增量行值?
- c++ - gtest - 确保一个方法之前没有被调用,但可以在某个方法调用之后被调用
- python-3.x - BeautifulSoup 连接不同段落中的单词
- python - 确定特定文件中元组中每个元素的 count = 0 - 如果为 0,则标记该元素
- three.js - 如何在不清除以前的渲染通道的情况下应用后处理 EffectComposer 渲染通道?
- javascript - 样式组件末尾的字符串是什么?
- javascript - onkeyup、onkeydown 和 onpaste 事件在 Android 设备上不起作用
- sql - 应用程序设计强制查询结构。查询从 Join 返回重复的结果。如何使用有限的选项修复结果集?
- r - R.Shiny 将输入转换为字符串
- sql - 计数不提供总值