ClientSignRecommand.php 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. <?php
  2. namespace app\common\model;
  3. use think\Model;
  4. use app\common\library\Redis;
  5. class ClientSignRecommand extends Model
  6. {
  7. // 表名
  8. protected $table = 'client_sign_recommand';
  9. // 自动写入时间戳字段
  10. protected $autoWriteTimestamp = 'int';
  11. // 定义时间戳字段名
  12. protected $createTime = 'createtime';
  13. protected $updateTime = 'updatetime';
  14. // 追加属性
  15. protected $append = [
  16. 'sex_text',
  17. 'status_text'
  18. ];
  19. public function getSexList()
  20. {
  21. return ['1' => __('Sex 1'),'2' => __('Sex 2')];
  22. }
  23. public function getStatusList()
  24. {
  25. return ['normal' => __('Normal'),'hidden' => __('Hidden')];
  26. }
  27. public function getSexTextAttr($value, $data)
  28. {
  29. $value = $value ? $value : $data['sex'];
  30. $list = $this->getSexList();
  31. return isset($list[$value]) ? $list[$value] : '';
  32. }
  33. public function getStatusTextAttr($value, $data)
  34. {
  35. $value = $value ? $value : $data['status'];
  36. $list = $this->getStatusList();
  37. return isset($list[$value]) ? $list[$value] : '';
  38. }
  39. /**
  40. * 根据性别获取推荐书籍
  41. * @param bool $sex 1 = 男 , 2 = 女
  42. * @return false|mixed|\PDOStatement|string|\think\Collection
  43. * @throws \think\db\exception\DataNotFoundException
  44. * @throws \think\db\exception\ModelNotFoundException
  45. * @throws \think\exception\DbException
  46. */
  47. public function getBooksBySex($sex = '1'){
  48. $redis = Redis::instance();
  49. $key = 'CSRB:'.$sex; //客户端推荐书库
  50. if(!$redis->exists($key)){
  51. $source = $this->where(['status'=>'normal','sex'=>$sex])->select();
  52. if(empty($source)){
  53. return null;
  54. }
  55. foreach($source as $item){
  56. $redis->sadd($key,$item['book_id'].':'.$item['book_name']);
  57. }
  58. $redis->expire($key,86400);
  59. if(count($source) >= 3){
  60. shuffle($source);
  61. return array_slice($source,0,3);
  62. }
  63. return $source;
  64. }else{
  65. $data = array();
  66. $source = $redis->srandmember($key,3);
  67. foreach($source as $item){
  68. $map = explode(':',$item);
  69. array_push($data,['book_id'=>array_shift($map),'book_name'=>implode($map)]);
  70. }
  71. return $data;
  72. }
  73. }
  74. }