接上一篇 基于yii2的blog系统开发4:

第十一步 标签处理

老师视频4.8节地址:https://v.youku.com/v_show/id_XMTczODc4MTkyNA==.html
修改common/models/Post.php,增加如下代码:

//标签处理
    private $_oldTags;
    public function afterFind()
    {
        parent::afterFind();
        $this->_oldTags = $this->tags;
    }

    public function afterSave($insert,$changedAttributes)
    {
        parent::afterSave($insert,$changedAttributes);
        Tag::updateFrequency($this->_oldTags,$this->tags);
    }

    public function afterDelete()
    {
        parent::afterDelete();
        Tag::updateFrequency($this->tags,'');
    }

修改common/models/Tag.php,增加如下代码:

 public function stringToArray($tag)
    {
        $tmp = explode(',', $tag);
        return $tmp;
    }

    public function updateFrequency($oldt,$newt)
    {
        $old = self::stringToArray($oldt);
        $new = self::stringToArray($newt);
        $del = array_diff($old, $new);
        $add = array_diff($new, $old); //$new里有而$old里没有的值

        foreach($del as $item1){
            $one = Tag::findOne(['name'=>$item1]);
            if($one){
                if($one->frequency>1)
               {
                    $one->frequency-=1;
                    $one->save();
                }else{
                    $one->delete();
                }
            }
        }

        foreach($add as $item2){
            $one2 = Tag::findOne(['name'=>$item2]);
            if($one2){
                    $one2->frequency+=1;
                    $one2->save();
            }else{
                $one2 = new Tag();
                $one2->frequency=1;
                $one2->name = $item2;
                $one2->save();
            }
        }
    }

注意,自定义public函数,在另外一个public函数中调用的时候前面加上self::,否则找不到