一、创建数据(自动创建)
Thinkphp可以帮助快速的创建数据对象,最典型的应用就是自动根据表单数据创建数据对象,这个优势在一个数据表的字段非常之多的情况下尤其明显。
// 实例化User模型
$User = M('User');
// 根据表单提交的POST数据创建数据对象
$User->create();
// 把创建的数据对象写入数据库
$User->add();
没有调用add或者save方法之前,我们都可以改变create方法创建的数据对象,例如:
$User = M('User');
$User->create(); //创建User数据对象
$User->status = 1; // 设置默认的用户状态
$User->create_time = time(); // 设置用户的创建时间
$User->add(); // 把用户对象写入数据库
二、自动验证(必须通过自动创建中的create方法才能生效)
1、实例化数据表的时候需要用D,进行下面的操作的时候,会先去Model里面寻找一下,有没有关于自动验证和自动完成的东西。
2、在Model文件夹里面写一个类:
(1)文件名:UserModel.class.php
(2)文件内容:
<?php
class UserModel extends Model{
protected $_validate=array(
array('code','require','验证码必须填写!'),
array('code','checkCode','验证码错误!',0,'callback',1),
array('username','require','用户必须填写!'),
array('username','','用户已经存在',0,'unique',1),
array('username','/^\w{6,}$/','用户名必须6个字母以上',0,'regex',1),
array('repassword','password','确认密码不正确',0,'confirm'),
);
protected function checkCode($code){
if(md5($code)!=$_SESSION['code']){
return false;
}else{
return true;
}
}
}
?>
三、自动完成(必须通过自动创建中的create方法才能生效)
具体步骤和自动验证一样
文件内容:
<?php
class MessageModel extends RelationModel{
protected $_auto=array(
array('time','time',1,'function'),
array('uid','getId',1,'callback')
);
protected function getId(){
return $_SESSION['id'];
}
}
?>