How to duplicate database record in Yii with 1 line

Well this will be quick since Yii is so powerful in their active record implementation. In Yii, if you ever want to duplicate a database record, all you have to do is to issue the following line.

$model = $this->loadModel($id); // record that we want to duplicate
$mode->id = null;
$model->isNewRecord = true;
if($model->save()){
//duplicated
}

The above implementation is pretty straight forward, we load the database record into a variable called model and set its primary key to null. Next, we set the variable isNewReocord to true and save the model. Once the model is saved, you will get yourself a new duplicated data where the Id is different from the one you just loaded. (well, there's more than 1 line but the key word to this is isNewRecord =x)

Share
Livedrive Simple, Secure Online Backup Increase sales with social commerce at BigCommerce. Learn More!