FollowRecommand.php 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. <?php
  2. namespace app\common\model;
  3. use think\Model;
  4. use app\common\library\Redis;
  5. class FollowRecommand extends Model
  6. {
  7. // 表名
  8. protected $table = 'follow_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'),'status' => __('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. * @param $isWater
  43. * @return false|mixed|\PDOStatement|string|\think\Collection
  44. * @throws \think\db\exception\DataNotFoundException
  45. * @throws \think\db\exception\ModelNotFoundException
  46. * @throws \think\exception\DbException
  47. */
  48. public function getBooksBySex($sex = '1',$isWater=false){
  49. $redis = Redis::instance();
  50. $key = $isWater ? 'FRB:W:'.$sex : 'FRB:'.$sex;
  51. $waterWhere = $isWater ? ' and classify_white_list=1 ' : '';
  52. if(!$redis->exists($key)){
  53. $obj = $this->alias('fr')->where(['fr.status'=>'normal','fr.sex'=>$sex]);
  54. $obj->join('book','book.id=book_id and book.state=1 '.$waterWhere,'inner');
  55. $source = $obj->select();
  56. if(empty($source)){
  57. return null;
  58. }
  59. foreach($source as $item){
  60. $redis->sadd($key,$item['book_id'].':'.$item['book_name']);
  61. }
  62. $redis->expire($key,900);
  63. if(count($source) >= 3){
  64. shuffle($source);
  65. return array_slice($source,0,3);
  66. }
  67. return $source;
  68. }else{
  69. $data = array();
  70. $source = $redis->srandmember($key,3);
  71. foreach($source as $item){
  72. $map = explode(':',$item);
  73. array_push($data,['book_id'=>array_shift($map),'book_name'=>implode($map)]);
  74. }
  75. return $data;
  76. }
  77. }
  78. }