我正在尝试将重置函数添加到codeigniter的迁移中。以下是我的代码:
class Migration extends Backend_Controller {
public function __construct()
{
parent::__construct();
$this->load->library('migration');
}
public function index()
{
//...
}
public function reset()
{
$this->migration->version(1);
$this->db->truncate('ci_sessions');
$this->migration->current();
}
}
返回错误:
Fatal error: Cannot redeclare class Migration_Create_geo_data in D:web_projectsvProjectframeworkapplicationmigrations 02_create_geo_data.php on line 44
如果我把它们分开运行,一切都会好起来的。当在一起时,它会产生错误。知道吗?
此错误很可能是由于将迁移设置为在表不存在且缓存数据未立即更新的情况下创建表而导致的。
迁移脚本调用DB_forge::create_table
方法,该方法使用两个参数。参数一是表名,参数二是可选的。它是if_not_exists
标志。但是,默认值为false;如果设置为true,则只有在表不存在的情况下才会创建表。
如果您的表是在if_not_exists
参数设置为false的情况下创建的,则缓存问题(可能)永远不会发生:
$this->dbforge->create_table('table_name');
如果创建表时if_not_exists
参数设置为true,则在重新加载迁移时需要强制更新缓存。
$this->dbforge->create_table('table_name', TRUE);
这里有几个选项可以避免这个问题:
- 仅将表名作为参数发送给
create_table
方法 migration->version(0)
调用后取消设置data_cache['table_names']
如果你选择选项2,这里有一个有效的方法:
public function reset() {
$this->load->library('migration');
if (!$this->migration->version(0)) {
echo $this->migration->error_string();
}
// unset table cache - this will force it to update
unset($this->db->data_cache['table_names']);
if (!$this->migration->current()) {
echo $this->migration->error_string();
}
}
除此之外,迁移文件还会自动加载并保存在会话中。我在system/librarys/Migration.php:include $f[0];
中将此行更改为include_once $f[0];
最有可能的是,您通过复制/粘贴以前的迁移&现在有两个迁移文件,它们具有声明为的相同类
即
class Migration_Add_blog extends CI_Migration
在两个文件中