我已经在Codeigniter3中使用CI提供的Migration
库并在在线教程的帮助下为数据库创建了迁移文件。我的迁移文件如下所示,
<?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()
方法创建一个方法来删除数据库中的所有表。我在文档中找不到任何关于这一点的参考。
发布于 2019-04-19 03:00:13
我使用了下面的迁移控制器,效果很好。
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
,例如。将导致调用Migration_Leave_tracker::down()`的http://example.com/migrator/migrate/0
。(至少对我来说是这样。)
时间戳编号也有效,但对于“最终向下”,使用零作为URL的参数。换句话说,只需像以前一样使用http://example.com/migrator/migrate/0
进行顺序编号。
https://stackoverflow.com/questions/55705133
复制相似问题