作者:手机用户2702938540 | 来源:互联网 | 2014-06-12 18:37
thinkphp3.1框架中的案例blog,添加日记的同时可以添加标签tag,但仅此而已,当删除日记时,标签并没有被删除掉,从而造成think_tagged表和think_tag累积了垃圾数据,为了实现删除日记的同时也一起清理掉.
thinkphp3.1框架中的案例blog,添加日记的同时可以添加标签tag,但仅此而已,当删除日记时,标签并没有被删除掉,从而造成think_tagged表和think_tag累积了垃圾数据,为了实现删除日记的同时也一起清理掉think_tagged表和think_tag那些过时的数据,我写了一个函数,在看下面函数时,要先弄清think_tagged表、think_tag和think_blog表的关联关系.
函数如下:
- public function deltag($recordId){
-
- $condition['recordId'] = $recordId;
-
- $tagged=M('Tagged');
- $taggedlist= $tagged->where($condition)->select();
-
- $taggedids=array();
-
- $tagIds=array();
-
- foreach ($taggedlist as $key => $value) {
-
- $tagIds[]=$value['tagId'];
-
- $taggedids[]=$value['id'];
- }
-
- foreach ($tagIds as $tagIdk => $tagIdv) {
-
- $tagId=$tagIdv;
-
- $tag=D('Tag');
-
- $tagvo=$tag->where('id='.$tagId)->find();
-
- $count=intval($tagvo['count']);
-
- if($count==1){
-
- $tag->where('id='.$tagId)->delete();
-
- }elseif($count > 1){
-
- $tag->where('id='.$tagId)->setDec('count',1);
-
- }
- }
-
- foreach ($taggedids as $taggedid_k => $taggedid_v) {
-
- $tagged->where('id='.$taggedid_v)->delete();
-
- }
-
-
- }
函数写好了,怎么使用呢?方法很简单,我们来看一下删除日记的函数:
- public function delete() {
-
- $model = M("Blog");
- if (!emptyempty($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() 里调用,如下:
- public function delete() {
-
- $model = M("Blog");
- if (!emptyempty($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了.