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->