Phalcon Multi模块普通模型魔法吸气器无法正常工作

时间:2016-04-15 14:01:45

标签: php model phalcon multi-module

我正在使用具有多模块结构的Phalcon PHP,我想在我的对象上使用魔法getter,但是当我尝试执行var_dump时,getter为null。

代码段模型用户

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

魔术吸气剂使用

public function addAction() {

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

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

  echo city->name;

}

你知道为什么这个神奇的吸气剂$user->getCity();不起作用吗?

感谢。

1 个答案:

答案 0 :(得分:1)

我找到了解决方案。

我必须在关系中定义命名空间和别名,如下所示:

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

希望有所帮助