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

vik*_*tra 4 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'
Run Code Online (Sandbox Code Playgroud)

在不使用$ 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);
    }           
}
Run Code Online (Sandbox Code Playgroud)

问候

小智 10

我想你在谈论一个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\'');
Run Code Online (Sandbox Code Playgroud)

正如你所说

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 */
Run Code Online (Sandbox Code Playgroud)