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.

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



401

I think this document URL can help you



82.6k
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.1k
edited Jan '19

@quasipickle email notification with PHP code has bug screenshot

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