Copy rows from one table to another

I have two identical tables and I need to copy an entire row from a table to another.


INSERT Table2

SELECT * FROM Table1

WHERE id=$id

Can I do the same above, using Active Record ?

No.

Ok, can you suggest an alternative way to achieve the same result?

  • With the newbie must have patience :slight_smile: -



$connection->createCommand('INSERT Table2 SELECT * FROM Table1 WHERE id=$id')->execute();



shouldn’t query be double qouted? Is this example safe?

if he really want to use AR maybe something like this:




$model1 = Model1::findOne($id);

$model2 = new Model2();

$model2->setAttributes($model1->getAttributes(), false);

$model2->save(false); 



Well! Thank you very much. Works. I dont’know why I clone all the records, but this is the right way. Thank you again.

I will try your suggestion, Dawid… Thank you. I will tell you

Simply perfect. Works out of the box. You are my hero! Thank you again!

The variant with models will actually get all the data from DB and then set it. It’s less efficient.

As for connection and params escaping it’s better to this way:


$connection

    ->createCommand('INSERT Table2 SELECT * FROM Table1 WHERE id=:id')

    ->bindValue(':id', $id)

    ->execute();

Thank you samdark, "createCommand" it is very powerful