如何使用codeigniter活动记录中选择插入记录 [英] How to insert records using select in codeigniter active record

查看:165
本文介绍了如何使用codeigniter活动记录中选择插入记录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用codeIgniter活动记录类来实现一个SQL查询。查询看起来是这样的。

I want to implement a sql query using CodeIgniter Active Record class. The query looks like this..

INSERT california_authors (au_id, au_lname, au_fname)
SELECT au_id, au_lname, au_fname
FROM authors
WHERE State = 'CA'

这是有可能在codeIgniter不使用$这个 - > DB - >查询方法?

Is this possible in CodeIgniter without using the $this->db->query method?

解决方案

$this->db->select('au_id, au_lname, au_fname');
$this->db->from('california_authors');
$this->db->where('state', 'CA');
$query = $this->db->get();

if($query->num_rows()) {
    $new_author = $query->result_array();

    foreach ($new_author as $row => $author) {
        $this->db->insert("authors", $author);
    }           
}

问候

推荐答案

我觉得你是在谈论AA SELECT ... INSERT查询,在活动记录类没有一个方法来做到这一点,但有两种方法要做到这一点

I think you are talking about a a SELECT ... INSERT query, on the active record class there is not a method to do that, but there are two ways to do it

1)

$query = $this->db->query('INSERT california_authors (au_id, au_lname, au_fname)
                           SELECT au_id, au_lname, au_fname
                           FROM authors
                           WHERE State = \'CA\'');

正如你所说

和2),您可以可以做到这一点,使用的是什么卡莱说,

And 2) you can can do this, using what Calle said,

$select = $this->db->select('au_id, au_lname, au_fname')->where('state', 'CA')>get('california_authors');
if($select->num_rows())
{
    $insert = $this->db->insert('california_authors', $select->result_array());
}
else
{ /* there is nothing to insert */

这篇关于如何使用codeigniter活动记录中选择插入记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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