我使用 CI 提供的Migration
库并在在线教程的帮助下,在 Codeigniter 3 中为数据库创建了迁移文件。我的迁移文件看起来像这样,
<?php
class Migration_Leave_tracker extends CI_Migration {
public function up() {
$this->dbforge->add_field(array(
'id' => array(
'type' => 'INT',
'constraint' => 11,
'auto_increment' => TRUE
),
'emp_id' => array(
'type' => 'INT',
'constraint' => 11,
),
'start_date' => array(
'type' => 'DATE',
),
'end_date' => array(
'type' => 'DATE',
),
'created_date' => array(
'type' => 'DATETIME',
),
));
$this->dbforge->add_key('id', TRUE);
$this->dbforge->create_table('leave_tracker');
}
public function down() {
$this->dbforge->drop_table('leave_tracker');
}
}
在这里你可以看到我的迁移文件有两种方法,一种是up()
用于创建表,另一种是down()
可用于删除表的方法。
我有另一个控制器,带有运行迁移的方法,
public function migrate($version = null) {
$this->load->library('migration');
if ($version != null) {
if ($this->migration->version($version) === FALSE) {
show_error($this->migration->error_string());
} else {
echo "Migrations run successfully" . PHP_EOL;
}
return;
}
if ($this->migration->latest() === FALSE) {
show_error($this->migration->error_string());
} else {
echo "Migrations run successfully" . PHP_EOL;
}
}
根据 CI 文档,这段代码将创建所有迁移,我想在后台它将调用所有迁移类的 up()
方法来创建表。
现在我的问题是如何创建一个方法,该方法将使用迁移类的drop()
方法删除数据库中的所有表。我在文档中找不到任何参考。
我使用以下迁移控制器取得了良好的效果。
class Migrator extends CI_Controller
{
public function __construct($config = array())
{
parent::__construct($config);
$this->load->library('migration');
}
public function migrate($version = NULL)
{
$outcome = $this->migration->version($version);
if(is_string($outcome))
{
echo "Migration to version $outcome succeeded.";
}
elseif($outcome === TRUE)
{
echo "No migration was possible. Target version is the same as current version.";
}
else
{
echo $this->migration->error_string();
}
}
public function latest() //you could this for migration::current() too
{
$this->migration->latest();
}
}
假设在迁移中使用"顺序"编号,class Migration_Leave_tracker
在文件001_Migration_Leave_tracker.php
然后浏览到http://example.com/migrator/migrate/1
将运行Migration_Leave_tracker::up()
。
要从该恢复,只需使用较低的序列号调用migrate
,例如。 http://example.com/migrator/migrate/0
这将导致调用Migration_Leave_tracker::d own(('。(至少对我来说是这样。
时间戳编号也有效,但对于"最终下降",请使用零作为 URL 的参数。换句话说,只需使用http://example.com/migrator/migrate/0
就像对顺序编号所做的那样。