如何在codeigniter活动记录中使用select插入记录

时间:2010-07-29 08:29:25

标签: activerecord codeigniter batch-insert

我想使用CodeIgniter Active Record类实现sql查询。查询看起来像这样..

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

在不使用$ this-> db->查询方法的情况下,CodeIgniter是否可以这样做?

解决方案

$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);
    }           
}

此致

4 个答案:

答案 0 :(得分:9)

我认为你在谈论一个SELECT ... INSERT查询,在活动记录类上没有一种方法可以做到这一点,但有两种方法可以做到这一点

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)你可以用Calle说的那样做,

$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 */

答案 1 :(得分:1)

如果您希望对查询执行进行良好控制,则可以通过3种方式进行SELECT ... INSERT:

1)使用codeigniter活动记录insert_batch(ci3)或insertBatch(ci4)(推荐):

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

2)使用codeigniter活动记录简单插入:

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

3)使用codeigniter活动记录查询执行:

$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 :(得分:0)

这是一个过时的帖子,但这对某人可能有用。

与Edgar Nadal答案相同,只是通过更安全的方式将参数传递给查询

$state = 'CA';
$sql = "
INSERT california_authors (au_id, au_lname, au_fname)
SELECT au_id, au_lname, au_fname
FROM authors
WHERE State = ?
";
$this->db->query($sql, array($state));

codeigniter-3.2.1

答案 3 :(得分:-2)

$query = $this->db->insert('california_authors', array('au_id' => 'value', 'au_lname' => 'value', 'au_name' => 'value'));

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

要检索结果,您可以执行以下操作:

$resultarr = $query->result_array(); // Return an associative array

手册中有很多相关信息。

http://codeigniter.com/user_guide/database/active_record.html