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 related records are saving ?

If I have 2 models Str and StrTranslations, where StrTranslations belongsTo Str. And if I i add new parent record (Str) with StrTranslations encapsulated as related Like

$myStr = new Str();
//$myStr->id = null; //want new ID from DB
$_related[0] = new StrTranslations();
//$_related->strid = null; //want to use $myStr->id assigned after DB INSERT
$_related[0]->value = "blabla";
$myStr->StrTranslations = $_related;
$myStr->save();

As you could notice i wanna to have myStr->id to be assigned by by DB insert, not by PHP code and after that wanna to reuse same id in related myStr->StrTranslations

Diggin the Mozel.zep https://github.com/phalcon/cphalcon/blob/master/phalcon/mvc/model.zep it looks like first Phalcon saves related records ($myStr->StrTranslations), not parent record ($myStr) by calling _preSaveRelatedRecords() then saves parent record by calling _doLowInsert()/_doLowUpdate() then re-saves related records _postSaveRelatedRecords() So related records actually are saved twice with same parent->save() call.

am I right ? It is not clear to me why related are saved first if anyway all saving happens withing a transation automatically ?

edited Jan '18

First you have to save Str so that the database assign an autoincrement id for the new record and then get the id to store it to StrTranslations.

$myStr = new Str(); 
//set data to $myStr
$myStr->loadFromJson($data); // I have made this function for load data from json..
$myStr->save();
$_related = new StrTranslations();
$_related->id_str = $myStr->id; // this will assign the newly added record id to the record for $_related.
$_related->save();