tp5模型事件回调函数中不能使用$this,使用会报错,涉及到数据库操作使用Db类,不能使用$this->save()之类的方式
如果回调函数中需要使用类内函数,需要将函数定义为static,通过self::调用
给个例子:分类删除前删除该分类的子分类
public static function init(){ self::event(‘before_delete‘, function ($data) { $sonids=self::getid($data[‘cate_id‘]); Db::table(‘sp_cate‘)->where([‘cate_id‘=>$sonids])->delete(); }); } //获取下级分类id static public function getid($pid){ static $ids=array(); $res= Db::table(‘sp_cate‘)->where(‘cate_pid‘,$pid)->field(‘cate_id‘)->select(); if($res!=null){ foreach ($res as $v){ if($v!=‘‘){ $ids[]=$v[‘cate_id‘]; self::getid($v[‘cate_id‘]); } } } return $ids; }
原文:https://www.cnblogs.com/jcydd/p/10800808.html