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:

Program:

...
public function initialize(){
    $this->hasMany('id','LOID\Model\Course','program_id',['alias'=>'courses']); 
}
...

Course:

...
public function initialize(){
    $this->belongsTo('program_id','LOID\Model\Program','id');
}
...

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

if($this->request->getPost('courses')){
    $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.phalconphp.com/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?



17.4k

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

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