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 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;
    }

}

}



4.5k
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 ]);
    }


43.9k

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.