staff.php模型中(该模型对应名为Staff的信息表):
<?php
namespace app\index\model;
use think\Model;
class Staff extends Model
{
}
?>
index.php控制器中:
<?php
namespace app\index\controller;
use app\index\model\Staff;
class Index
{
public function index()
{
$staff = Staff::get(1033);
return $staff->name.'的入职时间是:'.date('Y-m-d',$staff->hiredate);
}
}
?>
可以在模型中设计一个读取器,就不用每次都这么用了。
staff.php模型中:
<?php
namespace app\index\model;
use think\Model;
class Staff extends Model
{
protected function getHireDateAttr($hiredate)
{
return date('Y-m-d',$hiredate);
}
}
?>
index.php控制器中:
<?php
namespace app\index\controller;
use app\index\model\Staff;
class Index
{
public function index()
{
$staff = Staff::get(1033);
return $staff->name.'的入职时间是:'.$staff->hiredate;
}
}
?>
也可以这样:
index.php控制器中:
<?php
namespace app\index\controller;
use app\index\model\Staff;
class Index
{
public function index()
{
$staff = Staff::get(1033);
return $staff->hiredate;
}
}
?>
staff.php模型中:
<?php
namespace app\index\model;
use think\Model;
class Staff extends Model
{
protected function getHireDateAttr($hiredate,%data) //get...Attr是固定格式,只有这样的才是读取器,会自动读取...的内容
{
return $data['name'].'的入职时间是:'.date('Y-m-d',$hiredate);
}
}
?>
在model.php中添加:
protected function setHireDateAttr($hiredate)
{
return strtotime($hiredate);
}
在index.php中添加:
$staff = new Staff;
$staff->name = '左冷禅';
$staff->salary = 5000;
$staff->hiredate = '2014-10-23';
if($staff->save()){
return '新员工'.staff->name.',ID:'.$staff->id.',添加成功';
} else {
return $staff->getError();
}
这样会往数据库中添加一个转化为时间戳的hiredate。