使用codeigniter的活动记录语法增加mysql数据库的字段

2021-12-10 00:00:00 sql mysql codeigniter activerecord

我有以下 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:

This produces the following SQL:

"UPDATEusersSETvotes='(votes + 1)' WHEREid='44'"

"UPDATEusersSETvotes= '(votes + 1)' WHEREid= '44'"

它没有运行,但是这个 SQL 可以做我正在寻找的东西:"UPDATEusersSETvotes= (votes + 1) WHEREid='44'"` <--注意周围缺少引号 (votes + 1)

Which doesn't run, but this SQL does do what I'm looking for: "UPDATEusersSETvotes= (votes + 1) WHEREid= '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');

之所以有效,是因为第三个(可选)FALSE 参数告诉 CodeIgniter 不要用反引号 (') 保护生成的查询.这意味着生成的 SQL 将是:

UPDATE users SET votes= votes + 1 WHERE id='44'

如果您注意到,从 '(votes+1)' 中删除了反引号,这会产生将 votes 属性增加 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.

相关文章