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

A question on models and relationships

Following is the link to the question on Github.

https://github.com/phalcon/cphalcon/issues/2396

edited Apr '14

Others may not be able to follow the link to your question, soon, since the issue will be closed. So I will duplicate your question here.

I have model A which has a hasMany to another model B. Can I access model B public methods in A based on the relationship?

Class A extends Phalcon/Mvc/Model {
    //Members
    public $id;

    //Methods
    public function initialize() {
        $this->hasMany('id', 'B', 'a_id');
    }

    public function display() {
        $this->B->display();
    }
}

Class B extends Phalcon/Mvc/Model {
    //Members
    public $a_id;

    //Methods
    public function initialize() {
        $this->belongsTo('a_id', 'A', 'id');
    }

    public function display() {
        echo "Class B's method";
    }
}

I can do something similar in CakePHP using their ClassRegistry which is a repo for class objects, each with a key.



15.1k

I haven't tested this but logic suggestes, that since this is a hasMany relationship, B is going to be a collection of models; Therefore you must get a referance to an object within that collection.


    public function display() {
        $this->B->getFirst()->display();
    }

    OR

    public function display() {
        $this->B[0]->display();
    }

Thank you for the reply. You can only access static methods of a related model which seems to be the correct behavior. I resorted to using static methods for my needs instead of creating objects of related models.