CodeIgniter-活动记录插入(如果有新记录或重复更新) [英] CodeIgniter- active record insert if new or update on duplicate

查看:54
本文介绍了CodeIgniter-活动记录插入(如果有新记录或重复更新)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以在CodeIgniter中进行活动记录查询,以针对给定的密钥更新现有记录(如果已存在)或插入不存在的记录?

Is it possible to do an active record query in CodeIgniter that will update an existing record if one already exists or insert if it doesnt, for the given key?

我知道可以通过先查询以找到现有记录来完成此操作,但是我正在寻找最有效的方法.

I understand this could be done by first querying to find an existing record, but I'm seeking the most efficient approach.

推荐答案

基本上,您正在寻找的可能是

Basically what you are looking for might be this INSERT ... ON DUPLICATE KEY UPDATE - provided that you are using MySQL and your id is a unique key on the table.

您必须手动构造查询并将其传递给$this->db->query()函数,而不要传递任何内置的活动记录(如DB Driver的辅助函数).

You'd have to manually construct the query and pass to the $this->db->query() function instead of any built in active record like helper functions of the DB Driver.

示例:

$sql = 'INSERT INTO menu_sub (id, name, desc, misc)
        VALUES (?, ?, ?, ?)
        ON DUPLICATE KEY UPDATE 
            name=VALUES(name), 
            desc=VALUES(desc), 
            misc=VALUES(misc)';

$query = $this->db->query($sql, array( $id, 
                                       $this->validation->name, 
                                       $this->validation->desc, 
                                       $this->validation->misc
                                      ));

这篇关于CodeIgniter-活动记录插入(如果有新记录或重复更新)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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