We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

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=template_id=1, field3=template_info=green, field 4=table1_id=1

new record2=> field 1=id=2, field 2=template_id=2, field3=template_info=yellow, field 4=table1_id=1



11.6k
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?



2.2k

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?



11.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();


2.2k

Yes, this works. Thank you.