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.

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



7.1k
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. http://forum.phalconphp.com/help/markdown



14.1k

@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.5k

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

```php $this->hasMany("id", "\YOURMODELNAMESPACE\Articles", "userid", array( 'alias' => 'articles', 'foreignKey' => array( 'action' => Relation::ACTIONCASCADE ) )); ```

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

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



14.7k
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'            
    ));


14.7k

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