Solved thread

This post is marked as solved. If you think the information contained on this thread must be part of the official documentation, please contribute submitting a pull request to its repository.

How to copy records from a template table to another table with current id when creating new record.

I have a template table with records. When there is a new record created I want to copy the template table records to another table and add the id of the new record.

New record table1: New record=> field 1=id=1, field 2=info="hello there"

Template table: record1=> field 1=id=1, field 2=info="green" record2=> field 2=id=2, field 2=info="yellow"

Total table:

new record1=> field 1=id=1, field 2=templateid=1, field3=templateinfo=green, field 4=table1_id=1

new record2=> field 1=id=2, field 2=templateid=2, field3=templateinfo=yellow, field 4=table1_id=1

edited Jul '15

Hi,

it's easy (tested) (supposing your two models have exactly the same structure) $sourceRecord = mytemplatetable::findFirst(yourSortingParam); $sourceRecord->id = ""; (or use php unset()); $destRecord = new DestRecord(); $destRecord = $sourceRecord; $sourceRecord->create();

EDIT: maybe rather than using a "template" table you can use "default values" function of your database, no?



1.1k

It's a good idea to use "default values" but eventually the template table contains different templates (set of rows) so i want to chose which set of rows to copy. And the rows can vary from time to time. I think i need another solution, right?



7.6k
Accepted
answer

the solution I give you should work, and if you're working with models that differs from each other, instead of assigning one model instance to the other one, just assign recursively values from your template model instance to your new object then save it. ex: in your TotaltableController:

    <?php
    use Templatetable as template; //import your other model

    public function createRowFromTemplateAction($templateID) {
            $choosenTemplate = template::findFirst($templateID);
            $newRecord = new Totaltable();
            $newRecord->template_id = $choosenTemplate->id;
            $newRecord->info = $choosenTemplate->info;
            etc...
            $newRecord->create();


1.1k

Yes, this works. Thank you.