RedbagController.php 2.11 KB
<?php
namespace soa\controllers\v1;

use Yii;
use soa\controllers\BaseController;
use common\models\UserRedbag;
/**
 * Site controller
 */
class RedbagController extends BaseController
{
    
    /**
     * 用户领取一个红包
     * @return type
     */
    public function actionAdd()
    {
        $user_id = $this->requests('user_id');
        $room_id = $this->requests('room_id');
        if (!$user_id || !$room_id){
            $this->renderJson(Yii::$app->params['failed_code'],'缺少id');
        }
        
        $data = [
            'user_id'=>$user_id,
            'room_id'=>$room_id,
            'coupon_id'=>$coupon_id,
        ];
        $model = new UserRedbag;
        if ($model->load($data,'') && $model->save()){
            $this->renderJson(Yii::$app->params['success_code'],'',$ret);
        }else{
            $this->renderJson(Yii::$app->params['failed_code']);
        }
    }
    
    /**
     * 用户领取的红包列表
     * @return type
     */
    public function actionList()
    {
        $user_id = $this->requests('user_id');
        $room_id = $this->requests('room_id');
        if (!$user_id || !$room_id){
            $this->renderJson(Yii::$app->params['failed_code'],'缺少id');
        }
        
        $key = __CLASS__.__FUNCTION__.'user_id'.$user_id.'room_id'.$room_id;
        if (!$ret = $this->cache->get($key)){
            
            $ret = UserRedbag::find()
            ->where(['user_id'=>$user_id,'room_id'=>$room_id])
            ->orderBy(['create_time'=>SORT_DESC])
            ->select('coupon_id')->asArray()->column();     
            
            $dependency = new \yii\caching\DbDependency(['sql' => Yii::$app->db
                ->createCommand('SELECT MAX(update_time),count(*) FROM {{%user_redbag}} WHERE user_id=:user_id AND room_id=:room_id')
                ->bindValue(':user_id', $user_id)
                ->bindValue(':room_id', $room_id)
                ->getRawSql()]);
            $this->cache->set($key, $ret, Yii::$app->params['defaultCacheExpire'], $dependency);
        }
        
        $this->renderJson(Yii::$app->params['success_code'],'',$ret);
    }
    
}