CodeIgniter Forums
ActiveRecord Question - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: Archived Discussions (https://forum.codeigniter.com/forumdisplay.php?fid=20)
+--- Forum: Archived Development & Programming (https://forum.codeigniter.com/forumdisplay.php?fid=23)
+--- Thread: ActiveRecord Question (/showthread.php?tid=54389)



ActiveRecord Question - El Forum - 09-06-2012

[eluser]RobertB.[/eluser]
How can I do this with active record

Objective

Insert "Duplicate" all the content of a single column in a table to a column of another table.

This works
Code:
INSERT INTO tbl2 (`column tbl2`)
SELECT column tbl1
FROM   tbl1

This does not work
Code:
$this -> db -> insert('tbl2', ('column tbl2'));
$this -> db -> select('column tbl1');
$this -> db -> from('tbl1');

Thanks.


ActiveRecord Question - El Forum - 09-07-2012

[eluser]codemonkey[/eluser]
Even though this was hard to read, I would attack this like this.

Pull the data from the column and store it in a varible. Run another query to insert the varible data in the other column.


ActiveRecord Question - El Forum - 09-07-2012

[eluser]Aken[/eluser]
Active Record doesn't support that. You would have to write the SELECT query in the insert value's spot, but AR might auto-escape it.

You can try it - if it doesn't work, you'll need to do it manually (this is untested, just guessing off my memory):

Code:
$this->db->insert('table', array('column' => 'SELECT column FROM table2'));



ActiveRecord Question - El Forum - 09-09-2012

[eluser]RobertB.[/eluser]
Thanks for taking the time.

This is the only way that I have being able to make it work. As you can see I have to use the dbprefix in the query.
This way inserts all the ids of table 1 into a column in table 2.
Code:
$this -> db -> query("INSERT INTO dbprefix_tbl2 (tbl2.tbl1_id) SELECT tbl1.id FROM dbprefix_tbl1;");

The way that you suggest only insert 1 record.
Code:
$this -> db -> insert('tbl2', array('tbl2.tbl1_id' => 'SELECT tbl1.id FROM tbl1'));

Thanks


ActiveRecord Question - El Forum - 09-11-2012

[eluser]Unknown[/eluser]
thanks a lot
I have been trying to do this for several days.
But now its awesome