<?php

namespace common\models;

use Yii;

/**
 * This is the model class for table "{{%article_category}}".
 *
 * @property string $id
 * @property string $pid
 * @property string $name
 * @property string $ordid
 * @property integer $display
 */
class ArticleCategory extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return '{{%article_category}}';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['name', 'ordid', 'display'], 'required'],
            [['ordid', 'display'], 'integer'],
            [['name'], 'string', 'max' => 30],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'pid' => 'pid',
            'name' => '分类名称',
            'ordid' => '排序',
            'display' => '显示/隐藏',
        ];
    }
    public static function getCache($id=0){
        $cache = Yii::$app->cache;
        $data = $cache->get('article_category');
        if ($data === false) {
            $data = self::find()->select(['name','id'])->where(['display'=>1])->asArray()->indexBy('id')->orderBy(['ordid'=>'desc'])->column();
            $cache->set('article_category', $data);
        }
        if($id>0){
            return $data[$id];
        }
        return $data;
    }
    public function afterSave($insert, $changedAttributes){
        parent::afterSave($insert, $changedAttributes);
        $cache = Yii::$app->cache;
        $cache->delete('article_category');
        Article::updateAll(['cname'=>$this->name],'cid='.$this->id);
        return true;
    }
    public function afterDelete(){
        parent::afterDelete();
        $cache = Yii::$app->cache;
        $cache->delete('article_category');
        return true;
    }
}
