将数据库日期类型映射到 \datetime 或 Phalcon 中的任何其他对象
Mapping database date type to \datetime or any other object in Phalcon
我有一个 class,它的正文中包含另外两个 class:
class Leave
{
/**
* @var Day
*/
private $fistDay;
/**
* @var Day
*/
private $lastDay;
}
Day 是 php \Datetime class 上的一个简单容器,它实现了有关日期操作的一些逻辑以使代码更易于阅读。
当我将数据库中的 firstDay 列的类型指定为 'date' 时,phalcon 模型生成器将其映射为 'string',而我想改用我的自定义 class。有什么办法吗?再做一个 table 几天似乎有点矫枉过正 ;-)
干杯。
为了在从数据库中获取数据后应用一些格式,Phalcon 提供了一个 afterFetch
方法,您可以在您的模型上实现:
public function afterFetch()
{
$this->firstDay = new Day($this->firstDay);
$this->lastDay = new Day($this->lastDay);
}
我建议查看 documentation 以查看您可以通过这种方式管理的其他一些事件。
感谢@yergo,这是正确的地方:)在更新数据库记录之前,还需要使用 beforeSave() 和 afterSave() 再次生成对象字符串。
public function beforeSave()
{
$this->firstDay = $this->firstDay->getStringDate();
$this->lastDay = $this->lastDay->getStringDate();
}
public function afterFetch()
{
$this->firstDay = new Day($this->firstDay);
$this->lastDay = new Day($this->lastDay);
}
public function afterSave()
{
$this->firstDay = new Day($this->firstDay);
$this->lastDay = new Day($this->lastDay);
}
我有一个 class,它的正文中包含另外两个 class:
class Leave
{
/**
* @var Day
*/
private $fistDay;
/**
* @var Day
*/
private $lastDay;
}
Day 是 php \Datetime class 上的一个简单容器,它实现了有关日期操作的一些逻辑以使代码更易于阅读。
当我将数据库中的 firstDay 列的类型指定为 'date' 时,phalcon 模型生成器将其映射为 'string',而我想改用我的自定义 class。有什么办法吗?再做一个 table 几天似乎有点矫枉过正 ;-)
干杯。
为了在从数据库中获取数据后应用一些格式,Phalcon 提供了一个 afterFetch
方法,您可以在您的模型上实现:
public function afterFetch()
{
$this->firstDay = new Day($this->firstDay);
$this->lastDay = new Day($this->lastDay);
}
我建议查看 documentation 以查看您可以通过这种方式管理的其他一些事件。
感谢@yergo,这是正确的地方:)在更新数据库记录之前,还需要使用 beforeSave() 和 afterSave() 再次生成对象字符串。
public function beforeSave()
{
$this->firstDay = $this->firstDay->getStringDate();
$this->lastDay = $this->lastDay->getStringDate();
}
public function afterFetch()
{
$this->firstDay = new Day($this->firstDay);
$this->lastDay = new Day($this->lastDay);
}
public function afterSave()
{
$this->firstDay = new Day($this->firstDay);
$this->lastDay = new Day($this->lastDay);
}