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.

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.



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