1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889 |
- <?php
- namespace app\common\model;
- use think\Model;
- use app\common\library\Redis;
- class BookshelfRecommand extends Model
- {
- // 表名
- protected $table = 'bookshelf_recommand';
-
- // 自动写入时间戳字段
- protected $autoWriteTimestamp = 'int';
- // 定义时间戳字段名
- protected $createTime = 'createtime';
- protected $updateTime = 'updatetime';
-
- // 追加属性
- protected $append = [
- 'sex_text',
- 'status_text'
- ];
- public function getSexList()
- {
- return ['1' => __('Sex 1'),'2' => __('Sex 2')];
- }
- public function getStatusList()
- {
- return ['normal' => __('Status normal'),'hidden' => __('Status hidden')];
- }
- public function getSexTextAttr($value, $data)
- {
- $value = $value ? $value : $data['sex'];
- $list = $this->getSexList();
- return isset($list[$value]) ? $list[$value] : '';
- }
- public function getStatusTextAttr($value, $data)
- {
- $value = $value ? $value : $data['status'];
- $list = $this->getStatusList();
- return isset($list[$value]) ? $list[$value] : '';
- }
- /**
- * 根据性别获取推荐书籍
- * @param bool $sex 1 = 男 , 2 = 女
- * @return false|mixed|\PDOStatement|string|\think\Collection
- * @throws \think\db\exception\DataNotFoundException
- * @throws \think\db\exception\ModelNotFoundException
- * @throws \think\exception\DbException
- */
- public function getBooksBySex($sex = '1'){
- $redis = Redis::instance();
- $key = 'BKSR-RB:'.$sex;
- if(!$redis->exists($key)){
- $source = $this->where(['status'=>'normal','sex'=>$sex])->select();
- if(empty($source)){
- return null;
- }
- foreach($source as $item){
- $redis->sadd($key,$item['book_id'].':'.$item['book_name']);
- }
- $redis->expire($key,86400);
- if(count($source) >= 3){
- shuffle($source);
- return array_slice($source,0,3);
- }
- return $source;
- }else{
- $data = array();
- $source = $redis->srandmember($key,3);
- foreach($source as $item){
- $map = explode(':',$item);
- array_push($data,['book_id'=>array_shift($map),'book_name'=>implode($map)]);
- }
- return $data;
- }
- }
- }
|