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

Access related model information from events

Is there a way to access related models from event methods like beforeSave()? For example, I'd like to access (read) a piece of data from a parent model, like this:

<?php

class ParentEntity extends \Phalcon\Mvc\Model {
    public $some_property;

    public function getSomeProperty() {
        return $this->some_property;
    }

    ...
}

And in a related child model:

<?php

class ChildEntity extends \Phalcon\Mvc\Model {
    public function beforeSave() {
        $parentSomeProperty = $this->ParentEntity->getSomeProperty();
        // Do some calculations involving the parent property and some properties within the ChildEntity, and then save the result to a child property for saving with the child
    }

    ...
}

If I try to do this, Phalcon throws an exception about not being able to load the ParentEntity model. I can get what I want by using a ParentEntity::findFirst() and using the related ID since I've already saved the parent record at that point. However, whenever I get to a case where I haven't saved the record beforehand, I'm going to need a solution to this. It seems like Phalcon should let you access the related models during events. I can see a lot of different applications for that. Please let me know if there is a way to accomplish this.

I didn't write in the relations code, but that's assumed that I've set up the relations with Phalcon in the initialize() method.

edited Jul '15

HI Idennison,

I just attempted your exact setup here and was able to return values with no problems, can i see your initializaitons. Here was mine in the test setup.

parent Model

<?php
class Accounts extends Model
{
    public $id;
    $this->hasMany('id','Nova\Models\Child','childId', array(
        'alias' => 'files'
    ));

    public function testThing(){
        return $this->id;
    }
}

child model

<?php 
class child extends Model
{
    public function initialize(){
        $this->belongsTo('parentid', 'Nova\Models\Parent', 'id', array(
            'alias' => 'parent',
            'reusable' => true
        ));
    }

    public function beforeSave(){
        $test = $this->account->testThing();
    echo $bob;
    }
}

**Several edits for id mismatches when copy my initializes out.