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

One way model relation definitions?

Let's say I have 2 model classes - User and Comment (User hasMany Comments). However since my application is modular, the User class is unaware of Comment, since it may or may not be available depending on module availability. So, I cannot define the hasMany relationship in User, however it is defined as belongsTo in Comment.

When I try to pull the related Comment records from a User instance:

$items = $user->getRelated('Comment');

I get this error: There is no defined relations for the model "User" using alias "Comment"

If I add the hasMany definition in User, then it works.

Perhaps there is another way to pull the related records without building the actual queries every time?

i used to go a step back in this problem. I make a autoloader for all modukes in index.php so you can access all your classes everywhrre.

edited Oct '14

Yes, but that's not quite the same problem, isn't it? I solve the autoloading issue by matching namespaces to model file path, for example /module/articles/app/model/Comment.php is put in the articles/app/model namespace. Only the /module directory is added to autoloader.

Anyway, I don't think it resolves the question. One way I can think of is to add getRelated() method to BaseModel, something like this:

public function getRelated($model)
{
    try
    {
        $related = parent::getRelated($model);
    }
    catch (WhateverExceptionThatWas $exception)
    {
        // check if $model has a belongsTo relationship defined
        // ...

        if ($belongsTo)
        {
            // then
            $this->hasMany(...);

            $related = parent::getRelated($model);
        }
        else 
        {
            throw $exception;
        }
    }

    return $related;
}

I Understands your code, it will works. But please tell me then what do you exactly means with

"the User class is unaware of Comment, since it may or may not be available depending on module availability"

Note that If you have the class and the proper autoloader registered then you can define the relation with no problems.