<?php
namespace Admin\Controller;
use Think\Controller;
class GoodsController extends Controller {
public $gm;
public function __construct(){//自己实现construct方法的时候继承父类。防止重写,父类做了很多初始化工作
parent::__construct();
$this->gm = D('goods'); //传给一个属性,方便调用
}
//------------------------------------商品添加---
public function goodsadd(){
if(IS_POST){
if(!$this->gm->create($_POST)){//自动验证:看thinkphp手册。模型-自动验证-示例-----自动验证
echo $this->gm->getError();// 如果创建失败 表示验证没有通过 输出错误提示信息
exit;
}
//------------------------------------实例化上传类----
$upload = new \Think\Upload();// 实例化上传类
$upload->maxSize = 3145728 ;// 设置附件上传大小
$upload->exts = array('jpg', 'gif', 'png', 'jpeg');// 设置附件上传类型
$upload->rootPath = './Upload/'; // 设置附件上传根目录
$upload->savePath = ''; // 设置附件上传(子)目录
// 上传文件
$info = $upload->upload();
if(!$info) {// 上传错误提示错误信息
$this->error($upload->getError());
}else{// 上传成功
//------注意-----:可打印$info查看上传图片的信息
$img_path1 = './Upload/'.$info['goods_img']['savepath']; //上传的路径 路径/
$img_path2 = $info['goods_img']['savename'];//文件名
//---------------------------------------缩略图---
$image = new \Think\Image(); //-----------缩略图-----------
$image->open($img_path1.$img_path2);
// 按照原图的比例生成一个最大为230*230的缩略图并保存为thumb.jpg
$img_xiao = './Upload/thumb/'.$img_path2;
$image->thumb(230, 230)->save($img_xiao);
$this->gm->thumb_img = $img_xiao;
$this->gm->goods_img = $img_path1.$img_path2;
}
echo $this->gm->add()?'1':'0';//上传成功返回1
}
$this->display();
}
<?php
namespace Admin\Model;
use Think\Model\RelationModel;
class GoodsModel extends RelationModel{ //关联模型
public $_link = array(
'comment' => self::HAS_MANY,
);
public $insertFields = 'goods_name,goods_sn';//----------自动过滤----------
//不在这里面的过滤掉!
public $_auto = array( //----------自动填充----------
// array(完成字段1,完成规则,[完成条件,附加规则]),
array('add_time','time',3,'function'),
);
public $_validate = array( //----------自动验证----------
// array(验证字段1,验证规则,错误提示,[验证条件,附加规则,验证时间]),
array('goods_name','3,12','你这个傻子,名字不对','1','length','3'),
array('goods_sn','','你这个傻子,货号不对','1','unique','3'),
array('shop_price','pr','shop_price错了','1','callback','3'),//shop_price验证调用pr函数,成功与否取决于pr函数
);
public function pr(){
return turn;
}
}