使用codeigniter的活动记录语法增加mysql数据库的字段 [英] Increment field of mysql database using codeigniter's active record syntax

查看:34
本文介绍了使用codeigniter的活动记录语法增加mysql数据库的字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

这篇关于使用codeigniter的活动记录语法增加mysql数据库的字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆