query()->insertGetId($data); // 如果操作失败 if( !$id ) return $id; // 更新缓存 $this->getList(true); // 返回结果 return $id; } /** * 添加数据 * */ public function edit($id,$data) { // 更新时间 $data['update_time'] = time(); // 写入数据表 $result = $this->query()->where(['id'=>$id])->update($data); // 如果操作失败 if( !$result ) return $result; // 更新缓存 $this->getList(true); // 返回结果 return $result; } /** * 获取列表 * @param bool $force 是否强制更新 * */ public function getList($force = false) { // 结果数据 $list = $force ? [] : cache('admin:redpacket:active:reward:list'); // 不存在数据 if ( !$list ) { // 从数据库获取数据 $data = $this->query()->where([['status','=',0]])->get(['id','reward_total','money','probability','active_id']); // 是否有数据 $data = $data ? $data->toArray() : []; // 循环处理数据 $list = []; // 进行更新 foreach ($data as $value) { // 重组数据 $list[$value['id']] = $value; } // 存起来 cache(['admin:redpacket:active:reward:list'=>$list]); } // 返回结果 return $list; } /** * 获取配置平台对应的应用数据 * * @param array 用户ID * @param string 指定字段 * */ public function getOne($id,$field='') { // 获取列表数据 $list = $this->getList(); // 获取数据 $one = isset($list[$id]) ? $list[$id] : []; // 返回值 return empty($field) ? $one : ( isset($one[$field]) ? $one[$field] : null); } /** * 获取列表 * @param int $lotteryId 抽奖活动ID * */ public function getListByLottery($lotteryId) { // 结果数据 $data = $this->getList(); // 返回结果 $list = []; // 循环处理 foreach ($data as $value) { // 获取数据 if( $lotteryId == $value['active_id'] ) $list[] = $value; } // 追加一个谢谢参与 if( $list ) array_unshift($list,['id'=>0,'reward_total'=>0,'money'=>0,'probability'=>0,'active_id'=>$lotteryId]); // 返回结果 return $list; } /** * 获取抽奖结果 * @param array $reward 奖品列表 * */ public function getRewardResult($reward){ // 从0开始 $offset = 0; // 随机数,包含起始值,不含结束值 $randInt = random_int($offset,10000); // 中奖下标 $index = 0; // 循环奖品 foreach ($reward as $key => $value) { // 概率为0 或者产品份数为0,不参与 if( $value['probability'] <= 0 || $value['reward_total']<= 0 ) continue; // 开始数值 $start = $offset; // 结束数值 $end = $value['probability'] ? $start + intval($value['probability'] * 100) : 0; // 重新计算开始数值 $offset = $end ? $end : $offset; // 区间内即抽中 if( $start <= $randInt && $end >= $randInt ) $index = $key; } // 是否中奖,以及奖项下标 return $index; } }