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

Relationship with models not working

I have two Models:

Multiple\Backend\Models\Users

Multiple\Backend\Models\UserType

In User model class inside initialize():

 public function initialize() {
        $this->belongsTo("user_type_id", "UserType", "user_type_id", array(
            'alias' => "user_type"
        ));
 }

And in UserTypeModel:

 public function initialize(){
        $this->setSource("user_type");
        $this->hasMany("user_type_id", "Users", "user_type_id", array('alias' => "users" ));
 }

in wherever controller I call Users::find() method and acess UserType return:

 $users = Users::find();
 foreach($users as $user){
    echo $user->user_type->user_type_descr;
 }

And return a Exception: Model 'UserType' could not be loaded;

where I am going wrong?



1.7k

I strongly believe the problem should come from your mixing underscore naming with camel-casing...check check and tweak all your UserType namings and see



16.0k
Accepted
answer
edited Aug '15

you need to put the full namespace path even if both models are in the same directory: Multiple\Backend\Models\UserType and for users: Multiple\Backend\Models\Users



11.6k
edited Aug '15

i'm not sure that is related to soft relationship or cause I use the framework the wrong way, but I've noticed that in some case it's needed to first initialize an instance of a foreign model to be able to use it later in the controller (using another new instance) to avoid such 'not found' errors. So in the initialize() func I just add $myForeignModel = new Foreignmodel();

edited Aug '15

Thanks Stefan. Its working! =) but that should not work using only the model name, as both has the same namespace?

you need to put the full namespace path even if both models are in the same directory: Multiple\Backend\Models\UserType and for users: Multiple\Backend\Models\Users

the reason behind that is because your model is being added to the modelsManager and then used from there. On this point if you don't put the full path, the framework will search it somewhere in the 'root'. I think this behavior only occur on multi module applications.