Tp5 模型事件是指在进行模型的写入操作的时候触发的操作行为,包括模型的save方法和delete方法。
模型事件只可以在调用模型的方法才能生效,使用查询构造器通过Db类操作是无效的
模型类支持before_delete、after_delete、before_write、after_write、before_update、after_update、before_insert、after_insert事件行为。
快捷注册(V5.0.4+)
V5.0.4+版本开始,系统提供了内置的事件注册的快捷方法,你可以用下面的方式替代
beforeInsert新增前
afterInsert新增后
beforeUpdate更新前
afterUpdate更新后
beforeWrite写入前
afterWrite写入后
beforeDelete删除前
afterDelete删除后
官方demo:
namespace app\index\model; use think\Model; class User extends Model { protected static function init() { User::beforeInsert(function ($user) { if ($user->status != 1) { return false; } }); } }
以下是处理商品模板使用方法说明:
model 模型代码:
<?php namespace app\admin\model; use think\Model; class Goods extends Model { protected $field=true; protected static function init() { Goods::beforeInsert(function ($goods) { // 新增前,生成商品主图的缩略图 if($_FILES['og_thumb']['tmp_name']){ $thumbName=$goods->upload('og_thumb'); } }); Goods::afterInsert(function($goods){ // 新增后,批量写入会员价格 $mpriceArr=$goods->mp; $goodsId=$goods->id; db('member_price')->insert(['mlevel_id'=>$k,'mprice'=>$v,'goods_id'=>$goodsId]); // 处理商品相册 if($goods->_hasImgs($_FILES['goods_photo']['tmp_name'])){ $files = request()->file('goods_photo'); foreach($files as $file){ // 移动到框架应用根目录/public/uploads/ 目录下 $info = $file->move(ROOT_PATH . 'public' . DS . 'static/uploads/goods'); if($info){ $photoName= $info->getFilename(); $ogphoto=date('Ymd').DS.$photoName; $bigphoto=date('Ymd').DS.'big_'.$photoName; $midphoto=date('Ymd').DS.'mid_'.$photoName; $smphoto=date('Ymd').DS.'sm_'.$photoName; $image = \think\Image::open(IMG_UPLAODS.'goods/'.$ogphoto); $image->thumb(500, 500)->save(IMG_UPLAODS.'goods/'.$bigphoto); $image->