如何使用活动记录模式在codeigniter中运行此MySQL查询
问题描述:
我正在使用ci并使用其活动记录模式访问数据库。我想更新using语句表像如何使用活动记录模式在codeigniter中运行此MySQL查询
UPDATE employee_barcode set `count` = `count` + 1
where barcode_id = 2
我尝试使用update语句这样
$data = array(
'count' => 'count' + 1,
);
$this->db->where('barcode_id', 2);
$this->db->update('employee_barcode', $data);
但结果是错误的。
我该怎么做?
答
这不起作用,因为$this->db->update
无法获得值count
,因此无法将1加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');