Solved thread

This post is marked as solved. If you think the information contained on this thread must be part of the official documentation, please contribute submitting a pull request to its repository.

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.1k

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



12.8k
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

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.