开发者

How to "reset" CodeIgniter active record for consecutive queries?

I'm using CodeIgniter and have a case where two tables (projects and tasks) need to be updated with a value right after one another (active column needs to be set to "n"). The code I am using is:

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'));
}

With this code, the projects table gets updated but the tasks 开发者_开发知识库table does not. If I comment out $this->db->update('projects', array('active' => 'n')); then the tasks table gets updated.

I reckon this has something to do with caching but I have tried flush_cache before the tasks db->update call but that didn't have any effect.

Can someone explain how consecutive update queries can be executed using CodeIgniter?


Use

$this->db->start_cache();

Before starting query building and

$this->db->stop_cache();

After ending query building. Also, use

$this->db->flush_cache();

After stop cache.


This works:

$this->db->flush_cache();

If you don't perform a get() or similar CI does not always clear the cache. The final code looks like this:

$this->db->from('table');
$this->db->where('field', $field);
$count = $this->db->count_all_results();
$this->db->flush_cache();


For version 3 of Codeigniter the correct way is:

$this->db->reset_query()

As found here: http://www.codeigniter.com/userguide3/database/query_builder.html#resetting-query-builder

And 2022 update for version 4:

$this->db->resetQuery();

As found here: https://codeigniter.com/user_guide/database/query_builder.html#resetting-query-builder


Try calling $this->db->reset(); after the first update call.

EDIT: meh, try $this->db->_reset_write(); to flush all traces of the query.


In the second update call, do you need the url conditional? if so, after you call the first update that data is no longer available for the second one. You will need to set again:

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 active record update supports the where condition to be passed in as an array of key => value as the 3rd parameter (also as a string but id recommend using the array instead)


try

$this->db->reconnect();

after your query.

Good day!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜