thinkphp3.1框架中的案例blog,添加日记的同时能够添加标签tag,但仅此而已。当删除日记时,标签并无被删除掉,从而形成
think_tagged表和think_tag累积了垃圾数据。为了实现删除日记的同时也一块儿清理掉think_tagged表和think_tag那些过期的数据,
我写了一个函数,在看下面函数时,要先弄清think_tagged表、think_tag和think_blog表的关联关系。php
函数以下:html
public function deltag($recordId){ $condition['recordId'] = $recordId;//获取日记的ID $tagged=M('Tagged'); $taggedlist= $tagged->where($condition)->select();//这里用select而不用find,由于一篇日记可能有多个标签 $taggedids=array();//声明一个数组,用来装think_tagged表的ID $tagIds=array();//声明一个数组,用来装think_tag表的ID foreach ($taggedlist as $key => $value) { $tagIds[]=$value['tagId'];//获取think_tag表的ID $taggedids[]=$value['id'];//获取think_tagged表的ID } //考虑到一篇日记可能有多个标签,因此这里对$tagIds做一下遍历 foreach ($tagIds as $tagIdk => $tagIdv) { $tagId=$tagIdv; $tag=D('Tag'); $tagvo=$tag->where('id='.$tagId)->find();//获取每一个$tagId对应的一条记录 $count=intval($tagvo['count']);//获取标签的数量 if($count==1){//若是$count==1,说明这个标签仅有这篇日记全部,删掉。 $tag->where('id='.$tagId)->delete(); }elseif($count > 1){//$count > 1,说明这个标签为多篇日记全部,不能删除,因此减1。 $tag->where('id='.$tagId)->setDec('count',1);//setDec使$count减1,注意thinkphp3.1的使用方法。 } } //下面是删除日记存在think_tagged表里的相关数据 foreach ($taggedids as $taggedid_k => $taggedid_v) { $tagged->where('id='.$taggedid_v)->delete(); } }
函数写好了,怎么使用呢?方法很简单。
咱们来看一下删除日记的函数web
public function delete() { //删除指定记录 $model = M("Blog"); if (!empty($model)) { $id = $_REQUEST[$model->getPk()]; if (isset($id)) { if ($model->where("id=" . $id)->delete()) { if ($this->__get('ajax')) { $this->ajaxReturn($id, L('_DELETE_SUCCESS_'), 1); } else { $this->success(L('_DELETE_SUCCESS_')); } } else { $this->error(L('_DELETE_FAIL_')); } } else { $this->error(L('_ERROR_ACTION_')); } } }
这个函数是放在Examples\Blog\Lib\Action\PublicAction.class.php这个公共类里的,
BlogAction.class.php类继承了其删除函数,咱们就把deltag($recordId)函数放在delete() 里调用,以下:
ajax
public function delete() { //删除指定记录 $model = M("Blog"); if (!empty($model)) { $id = $_REQUEST[$model->getPk()]; if (isset($id)) { $recordId=$id; $this->deltag($recordId); if ($model->where("id=" . $id)->delete()) { if ($this->__get('ajax')) { $this->ajaxReturn($id, L('_DELETE_SUCCESS_'), 1); } else { $this->success(L('_DELETE_SUCCESS_')); } } else { $this->error(L('_DELETE_FAIL_')); } } else { $this->error(L('_ERROR_ACTION_')); } } }
以上只适用删除单条日记的状况,固然如要批量删除日记,只要遍历删除blog的ID同时调用一下deltag($recordId)就OK了。
thinkphp
本文首发WBlog博客,欢迎转载!转载请注明本文地址,谢谢。 数组
本文地址:http://www.w3note.com/web/12.html 框架