首页 > 代码库 > Phalcon中使用namespace时如何进行model相关的操作
Phalcon中使用namespace时如何进行model相关的操作
Phalcon中的Model中使用了命名空间里如何定义关系映射?Phalcon的官方手册中未明确给出如何解决这个问题的方法。现提供给大家。方法如下,即是使用model中的alias选项即可。
<?php
namespace models;
class Robots extends \Phalcon\Mvc\Model
{
/**
*
* @var integer
*/
public $id;
/**
*
* @var string
*/
public $name;
/**
*
* @var string
*/
public $type;
/**
*
* @var integer
*/
public $year;
/**
* Independent Column Mapping.
*/
public function columnMap()
{
return array(
‘id‘ => ‘id‘,
‘name‘ => ‘name‘,
‘type‘ => ‘type‘,
‘year‘ => ‘year‘
);
}
public function initialize()
{
$this->hasMany( ‘id‘, ‘models\RobotsParts‘, ‘robots_id‘ , array( ‘alias‘ => ‘robotsParts‘ ));
$this->useDynamicUpdate(true);
\Phalcon\Mvc\Model::set( array( ‘phqlLiterals‘ => false ));
}
}
<?php
namespace models;
class Parts extends \Phalcon\Mvc\Model
{
/**
*
* @var integer
*/
public $id;
/**
*
* @var string
*/
public $name;
/**
* Independent Column Mapping.
*/
public function columnMap()
{
return array(
‘id‘ => ‘id‘,
‘name‘ => ‘name‘
);
}
public function initialize()
{
$this->hasMany( ‘id‘, ‘models\RobotsParts‘, ‘parts_id‘, array( ‘alias‘ => ‘robotsParts‘ ) );
$this->useDynamicUpdate( true );
}
}
<?php
namespace models;
class RobotsParts extends \Phalcon\Mvc\Model
{
/**
*
* @var integer
*/
public $id;
/**
*
* @var integer
*/
public$robots_id;
/**
*
* @var integer
*/
public$parts_id;
/**
*
* @var string
*/
public$created_at;
/**
* Independent Column Mapping.
*/
public function columnMap()
{
return array(
‘id‘ => ‘id‘,
‘robots_id‘ => ‘robots_id‘,
‘parts_id‘ => ‘parts_id‘,
‘created_at‘ => ‘created_at‘
);
}
public function initialize()
{
$this->belongsTo(‘robots_id‘,‘models\Robots‘,‘id‘,array(‘alias‘=> ‘robots‘ ) );
$this->belongsTo(‘parts_id‘,‘models\Parts‘,‘id‘,array(‘alias‘=> ‘parts‘ ) );
$this->useDynamicUpdate(true);
}
}
如不使用alias即会出现形如下错误:
Notice: Access to undefined property models\RobotsParts::parts in /Library/WebServer/Documents/phalcon/app/controllers/ModController.php on line 18
Notice: Trying to get property of non-object in /Library/WebServer/Documents/phalcon/app/controllers/ModController.php on line 18。
Phalcon中使用namespace时如何进行model相关的操作