CodeIgniter 查询:如何将列值移动到同一行中的另一列,并将当前时间保存在原始列中


CodeIgniter query: How to move a column value to another column in the same row and save the current time in the original column?

在我的数据库表中,我有两个日期时间列:LastCurrent。这些列允许我跟踪某人上次使用有效登录名登录我正在构建的服务的时间。

使用 CodeIgniter 的活动记录,是否可以更新行,以便Last值接收Current值,然后将Current值替换为当前日期时间?

尝试如下:

$data = array('current_login' => date('Y-m-d H:i:s'));
$this->db->set('last_login', 'current_login', false);
$this->db->where('id', 'some_id');
$this->db->update('login_table', $data);

请特别注意set()调用的第 3 个参数。 false阻止 CodeIgniter 引用第二个参数 - 这允许将值视为表列而不是字符串值。 对于任何不需要特殊处理的数据,您可以将所有这些声明集中到 $data 数组中。

上述代码生成的查询:

UPDATE `login_table`
SET last_login = current_login, `current_login` = '2018-01-18 15:24:13'
WHERE `id` = 'some_id'
$data = array( 
    'name'      => $_POST['name'] , 
    'groupname' => $_POST['groupname'], 
    'age'       => $_POST['age']
);
$this->db->where('id', $_POST['id']);
$this->db->update('tbl_user', $data);

如果您只想升级表行的单列,则可以使用如下方法:

$this->db->set('column_header', $value); //value that used to update column  
$this->db->where('column_id', $column_id_value); //which row want to upgrade  
$this->db->update('table_name');  //table name

是的,这是可能的,我想为 Rajeev 的答案提供一个稍微的替代方案,即不将 php 生成的日期时间格式字符串传递给查询。

关于如何在 UPDATE 查询中声明要 SET 的值的重要区别在于,它们不得作为文本字符串引用。

要防止 CodeIgniter 自动执行此"帮助",请使用具有第三个参数 falseset() 方法。

$userId = 444;
$this->db->set('Last', 'Current', false);
$this->db->set('Current', 'NOW()', false);
$this->db->where('Id', $userId);
// return $this->db->get_compiled_update('Login');  // uncomment to see the rendered query
$this->db->update('Login');
return $this->db->affected_rows();  // this is expected to return the integer: 1

生成的查询(取决于您的数据库适配器)如下所示:

UPDATE `Login` SET Last = Current, Current = NOW() WHERE `Id` = 444

演示了查询有效的证明:https://www.db-fiddle.com/f/vcc6PfMcYhDD87wZE5gBtw/0

在这种情况下,LastCurrent是MySQL关键字,但它们不是保留关键字,因此不需要反引号包装。

如果您的精确查询需要具有正确引用的标识符(表/列名称),则始终存在 protectIdentifiers()。