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

Related model save

Hello. I have two models: Plant and PlantTitle Relation is one to many ($plant->titles); I want to create new records for Plant and PlantTitle at the same time. Could you suggest best way to do it. I tried:

                $plant = new Plant([
                     'latin_title' => $this->request->getPost('latin_title'),
                     'creator_id' => 0,
                     'titles' => [new PlantTitle([
                             'language' => 'en',
                             'title' => $this->request->getPost('title'),
                     ])]
                 ]);
                $plant->save();

Plant is created, but PlantTitle isn't. As for now I see only one solution: save Plant, then create PlantTitle with new plant_id. Does anyone know more elegant solution? Thanks

P.S.: phalcon version is 3.4.0



411

I think this document URL can help you



125.7k
Accepted
answer
edited Jan '19

I just encountered this problem. It seems that related models can't be passed when creating a new object. They can be assigned afterwards though - before you save. So this should work:

$plant = new Plant([
     'latin_title' => $this->request->getPost('latin_title'),
     'creator_id'  => 0
 ]);

$plant->titles = [
    new PlantTitle([
        'language' => 'en',
        'title'    => $this->request->getPost('title'),
     ])
];
$plant->save();

I've also modified your original post to have proper PHP highlighting. You can edit your post to see how I did that.



2.8k
edited Jan '19

@quasipickle email notification with PHP code has bug

I'm just a moderator - I don't work on Phosphorum. I suggest you file a ticket: https://github.com/phalcon/forum/issues

@quasipickle email notification with PHP code has bug