如何使用活动记录模式在codeigniter中运行此MySQL查询


How to run this MySQL query in codeigniter using active record pattern

我正在使用ci并使用其活动记录模式来访问数据库。我想使用之类的语句更新表格

UPDATE employee_barcode set `count` = `count` + 1
where barcode_id = 2

我试着使用像这样的更新语句

$data = array(
            'count' => 'count' + 1,
        );
$this->db->where('barcode_id', 2);
$this->db->update('employee_barcode', $data);

但结果是错误的。

我怎么能这么做?

这不起作用,因为$this->db->update无法获取count的值,因此无法向其添加1。您应该使用$this->db->select获取count的值,然后继续更新该值。

例如:

$this->db->where('barcode_id', 2);
$this->db->select('count');
$query = $this->db->get('employee_barcode');
$row = $query->row();
$this->db->where('barcode_id', 2);
$this->db->update('employee_barcode', array('count' => ($row->count + 1)));

试试这个。。

$this->db->set('count', '`count+1`', FALSE)
$this->db->where('barcode_id', 2);
$this->db->update('employee_barcode');