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 relationship

Hello!

I want to build a relationship between two models: User and Grade. It looks ok to me but I keep getting the next error:

Model 'Student' could not be loaded

I was looking on the forum in the searching of a fix, but I didn't succeed. A possible fix was to include the Models namespace as the second parameter when establishing the relationship in the initialize method, but this didn't do it. Any suggestions? I'd be grateful for any help :)

User model:

namespace Models;

use Phalcon\Mvc\Model;

class User extends Model

{

public $id;

public $username;

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

}

Grade model:

namespace Models;

use Phalcon\Mvc\Model;

class Grade extends Model

{

public $user_id;

public $value;

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

}

Controller:

namespace Controllers;

use Models\User;

use Models\Grade;

class IndexController extends ControllerBase {

public function indexAction()

{
    $u = User::find();
    foreach($u as $uu) {
        echo $uu->Grade->value;
    }

}

}



1.9k
Accepted
answer

My relations are set-up like below.

Models UserLogs and Roles are both in the same folder as the model User the code below belongs to.

  class Users extends BaseModel
  {
    ........................

    public function initialize()
    {
      // Set table name
      $this->setSource( 'users' );

      // Relations
      $this->hasMany( 'id', UserLogs::class, 'user_id', [ 'alias' => 'logs', 'reusable' => true ]);

      $this->belongsTo( 'role_id', Roles::class, 'id', [ 'alias' => 'role', 'reusable' => true ]);
    }


38.3k

Hi,

Model 'Student' could not be loaded

we can't see any Student Model in the code you have shown !!! above Also, when declaring your relations in the initialize() method, use full namespaced models (like Model\User) and, as Hoet said, use alias that are easily understandable.