We are moving our forum in GitHub Discussions. For questions about Phalcon v3/v4 you can visit here and for Phalcon v5 here.

Related records not saving

It seems every new project I start with Phalcon has me coming back to this same problem - related records just refuse to be saved sometimes.

I have a Program and a Course model, set up with the proper relationship:


public function initialize(){


public function initialize(){

In my controller, I assign a number of Courses to the Program:

    $courses = [];
    foreach($this->request->getPost('courses') as $name){
        $Course             = new Course();
        $Course->name       = $name;
        $Course->program_id = $Program->id;
        $courses[]          = $Course;
$Program->courses = $courses;

"courses" never gets saved though. As far as I can tell, this process is pretty much the same as the example here: http://docs.phalcon.io/en/latest/reference/models.html#storing-related-records. The only potential difference I can think of is that my courses table has a multi-column primary key (name and program_id).

What am I doing wrong?

edited Mar '14

Add this to your Course Model:

$this->belongsTo("program_id", '\LOID\Model\Program', "id", [
    "foreignKey" => [
        "message" => "The program_id does not exist on the Course model"

Thanks for your reply. I'm no longer having the problem, but for the life of me I can't figure out what I did to fix it. Could you explain why adding a foreignKey message would solve the problem?


You can add update() method at the end of your controller:

$Program->courses = $courses;
$Program->update(); //now courses will be added