简体   繁体   English

CodeIgniter Active Record从一个表插入另一个表

[英]CodeIgniter Active Record insert from one table to another

What is the syntax for inserting data from one table to another table, using codeigniter active record syntax? 使用codeigniter活动记录语法将数据从一个表插入另一个表的语法是什么? I tried the usual mysqli query and it works, but I want to use CodeIgniter Active Record syntax for consistency. 我尝试了通常的mysqli查询并且它可以工作,但我想使用CodeIgniter Active Record语法来保持一致性。

I tried playing with these CodeIgniter Active Record queries but still no luck: 我尝试使用这些CodeIgniter Active Record查询,但仍然没有运气:

function insert_into()  
{    
    $this->db->insert('table1');
    $this->db->set('to_column');  
    $this->db->select('from_column');
    $this->db->from('table2');
}

I think the best thing to accomplish that is fetching the data you want from one table using the get method, then using one of the query results grabber functions (like result() ), iterate over the rows one by one using the insert() method. 我认为最好的办法是使用get方法从一个表中获取所需的数据,然后使用其中一个查询结果抓取器函数(如result()),使用insert()逐个遍历行。方法。

Putting this in code: 把它放在代码中:

 $query = $this->db->get('table1'); foreach ($query->result() as $row) { $this->db->insert('table2',$row); } 

Of course, i suppose that table1 has exactly th same structure as table2 (the same column names and data types for each column). 当然,我认为table1与table2具有完全相同的结构(每列的列名和数据类型相同)。 If that is not the case, you will have to map the columns from one table to the another using assignments, but if that is the case your code will be more wide. 如果不是这种情况,则必须使用赋值将列中的列映射到另一个表,但如果是这种情况,则代码将更宽。

Copies $source_table into $archive_table: 将$ source_table复制到$ archive_table中:

if(($this->db->table_exists($source_table) && ($this->db->table_exists($archive_table)){
    if ($this->db->query("CREATE TABLE $archive_table LIKE $source_table")){
        if($this->db->query("INSERT $archive_table SELECT * FROM $source_table")){
           echo 'copied ok';
        }
     } 
}

Neater than looping over the entire result set and inserting one row at a time. 比循环整个结果集并一次插入一行更整洁。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM