我使用的是CodeIgniter,有一种情况,两个表(项目和任务)需要一个接一个地更新一个值(活动列需要设置为"n")。我使用的代码是:
function update($url, $id)
{
$this->db->where('url', $url);
$this->db->update('projects', array('active' => 'n'));
$this->db->where('eventid', $id);
$this->db->update('tasks', array('active' => 'n'));
}
使用此代码,项目表会得到更新,但任务表不会。如果我注释掉$this->db->update('projects', array('active' => 'n'));
,那么任务表就会更新。
我认为这与缓存有关,但在任务db->update
调用之前,我尝试过flush_cache
,但没有任何效果。
有人能解释一下如何使用CodeIgniter执行连续更新查询吗?
使用
$this->db->start_cache();
在开始查询构建和之前
$this->db->stop_cache();
结束查询生成后。此外,使用
$this->db->flush_cache();
停止缓存后。
这是有效的:
$this->db->flush_cache();
如果不执行get()或类似操作,则CI并不总是清除缓存。最后的代码如下:
$this->db->from('table');
$this->db->where('field', $field);
$count = $this->db->count_all_results();
$this->db->flush_cache();
对于Codeigniter的版本3,正确的方法是:
$this->db->reset_query()
如下所示:http://www.codeigniter.com/userguide3/database/query_builder.html#resetting-查询生成器
2022年第4版更新:
$this->db->resetQuery();
如下所示:https://codeigniter.com/user_guide/database/query_builder.html#resetting-查询生成器
在第一次调用update
之后尝试调用$this->db->reset();
。
EDIT:meh,尝试$this->db->_reset_write();
刷新查询的所有跟踪。
在第二次更新调用中,是否需要url条件?如果是这样,那么在调用第一次更新后,第二次更新的数据将不再可用。您需要再次设置:
function update($url, $id)
{
$this->db->where('url', $url);
$this->db->update('projects', array('active' => 'n'));
$this->db->where('url', $url);
$this->db->where('eventid', $id);
$this->db->update('tasks', array('active' => 'n'));
}
// Alternatively
function update($url, $id)
{
$where_bit = array(
'url' => $url,
);
$this->db->update('projects', array('active' => 'n'), $where_bit);
$where_bit['event_id'] = $id;
$this->db->update('tasks', array('active' => 'n'), $where_bit);
}
CI活动记录更新支持将where条件作为关键字=>值的数组作为第三个参数(也作为字符串,但id建议使用数组)传入
尝试
$this->db->reconnect();
在您的查询之后。
你好!