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

Model could not be loaded

Have these 2 tables in my db: Articles ( id, title, content, __#user_id ) Users ( id__, name, pwd)

And I did in my models: Articles:

public function initialize(){ $this->belongsTo("user_id", "Users", "id"); }

Users:

$this->hasMany("id", "Articles", "user_id");

When I do

$useArticles = $user->articles

I get : PhalconException:: Model 'Articles' could not be loaded



10.5k
Accepted
answer
edited Mar '14

Try this solution: replace your user Articles model NAMESPACE


for example if your Articles model is in Common namespace use: \Common\Articles

$this->hasMany("id", "\YOUR_MODEL_NAMESPACE\Articles", "user_id", array(
  'alias' => 'articles',
  'foreignKey' => array(
    'action' => Relation::ACTION_CASCADE
  )
));

foreign key settings is optional :and you can remove it.

  'foreignKey' => array(
    'action' => Relation::ACTION_CASCADE
  )

@sn0opr did you check if you havn't anywhere a typo? Check your classname of Articles and the filename.

edited Mar '14

@sn0opr pls read how to paste PHP code and paste it here, probably you did typo, not extend class by \Phalcon\Mvc\Model or something similar. https://forum.phalcon.io/help/markdown



22.8k

@a6oozar, Thank you not it works with namespace :), because I'm using modules so I have to put namespaces

Is it compulsory to set foreign key in mysql ?

@sn0opr can you share your code for part where you use model with relationship in your controller ?

@paanblogger it`s virtual foreign key configuarion and it's not mandatory to use it in your model relation.



1.7k

Thanks @a6oozar, this works for me.

Try this solution: replace your user Articles model NAMESPACE


for example if your Articles model is in Common namespace use: \Common\Articles

$this->hasMany("id", "\YOUR_MODEL_NAMESPACE\Articles", "user_id", array(
 'alias' => 'articles',
 'foreignKey' => array(
  'action' => Relation::ACTION_CASCADE
 )
));

foreign key settings is optional :and you can remove it.

 'foreignKey' => array(
   'action' => Relation::ACTION_CASCADE
 )


24.9k
edited Sep '14

Hm i try your selution but i get "boolean false": Controller: var_dump($user->getSessions()); Users initialize:

    $this->hasOne("id", "\Modules\Engine\Models\Sessions", "id", array(
        'alias' => 'sessions'            
    ));

Sessions initialize:

    $this->belongsTo("id", "\Modules\Engine\Models\Users", "id", array(
        'alias' => 'users'            
    ));


24.9k

Hmm just change Users model to hasMany relation and it work ...