MySQL数据库的使用codeigniter的活动记录语法增量场 [英] Increment field of mysql database using codeigniter's active record syntax
问题描述
我有以下的PHP的codeigniter它试图通过增加主动记录语法记录的字段脚本:
I have the following php-codeigniter script which attempts to increment a field of a record using active-record syntax:
$data = array('votes' => '(votes + 1)');
$this->db->where('id', $post['identifier']);
$this->db->update('users', $data);
这生成的SQL语句:
更新
用户设置
票 ='(票+ 1)'WHERE
ID ='44'
这并不运行,但是这个SQL所做的事,我找什么:
更新
用户设置
票 =(票+ 1),其中
ID ='44'
`< - 注意缺少引号各地(投票+ 1)
Which doesn't run, but this SQL does do what I'm looking for:
"UPDATE
usersSET
votes= (votes + 1) WHERE
id= '44'
"` <--Note the lack of quotes around (votes + 1)
有谁知道如何实现这种类型的查询与codeigniter的活动记录语法?
Does anyone know how to implement this type of query with codeigniter's active record syntax?
推荐答案
您可以做如下:
$this->db->where('id', $post['identifier']);
$this->db->set('votes', 'votes+1', FALSE);
$this->db->update('users');
这部作品的原因是第三个(可选)假参数告诉codeIgniter不是保护与反引号生成的查询()。这意味着,生成的SQL将是:版
更新用户SET票=票+ 1 WHERE ID ='44'
如果您发现,反引号从删除(投票+ 1)
,产生递增的选票属性1所期望的效果。
The reason this works is because the third (optional) FALSE parameter tells CodeIgniter not to protect the generated query with backticks ('
). This means that the generated SQL will be:
UPDATE users SET votes= votes + 1 WHERE id= '44'
If you notice, the backticks are removed from '(votes+1)'
, which produces the desired effect of incrementing the votes attribute by 1.
这篇关于MySQL数据库的使用codeigniter的活动记录语法增量场的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!