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

Phalcon Multi module common models magic getter not working

I'm using Phalcon PHP with multi modules structure and I want to use a magic getter on my object but the getter is null when I'm trying to do a var_dump.

Snippet Model Users

namespace Apps\Common\Models;

use Phalcon\Mvc\Model;

class Users extends Model{

   public $id;

   public $city_id;

   public $name;

   ...

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

Snippet Model City

namespace Apps\Common\Models;

use Phalcon\Mvc\Model;

class City extends Model{

   public $id;

   public $name;

   ...

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

Magic getter utilization

public function addAction() {

  $user = Users::findFirst(array(
    "id = :id:",
    "bind" => array('id' => 2)
  ));

  city = $user->getCity();  // This is null

  echo city->name;

}

Do you know why this magic getter $user->getCity(); doesn't work ?

Thanks.



41.3k
Accepted
answer

Oh I found the solution. I have to define the namespace and an alias in the relation like this :

namespace Apps\Common\Models;

use Phalcon\Mvc\Model;

class Users extends Model{

   public $id;

   public $city_id;

   public $name;

   ...

   public function initialize(){
       $this->belongsTo("city_id", "Apps\Common\Models\City", "id", array('alias' => 'City') );
   }
}