SignedRecommand.php 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. <?php
  2. namespace app\common\model;
  3. use think\Model;
  4. use app\common\library\Redis;
  5. class SignedRecommand extends Model
  6. {
  7. // 表名
  8. protected $table = 'signed_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' => __('Status normal'),'hidden' => __('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. * @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',$limit=3, $isWater=false){
  48. $redis = Redis::instance();
  49. $key = $isWater ? 'SED-RB:W:'.$sex : 'SED-RB:'.$sex;
  50. $waterWhere = $isWater ? ' and classify_white_list=1' : '';
  51. if(!$redis->exists($key)){
  52. $obj = $this->alias('sr')->where(['sr.status'=>'normal','sr.sex'=>$sex]);
  53. $obj->join('book','book.id=book_id and book.state=1'.$waterWhere,'inner');
  54. $source = $obj->select();
  55. if(empty($source)){
  56. return null;
  57. }
  58. foreach($source as $item){
  59. $redis->sadd($key,$item['book_id'].':'.$item['book_name']);
  60. }
  61. $redis->expire($key,900);
  62. if(count($source) >= $limit){
  63. shuffle($source);
  64. return array_slice($source,0,$limit);
  65. }
  66. return $source;
  67. }else{
  68. $data = array();
  69. $source = $redis->srandmember($key,$limit);
  70. foreach($source as $item){
  71. $map = explode(':',$item);
  72. array_push($data,['book_id'=>array_shift($map),'book_name'=>implode($map)]);
  73. }
  74. return $data;
  75. }
  76. }
  77. }