Collect.php 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118
  1. <?php
  2. namespace app\common\model;
  3. use think\Model;
  4. class Collect extends Model
  5. {
  6. // 表名
  7. protected $name = 'shop_collect';
  8. // 自动写入时间戳字段
  9. protected $autoWriteTimestamp = 'int';
  10. // 定义时间戳字段名
  11. protected $createTime = 'createtime';
  12. protected $updateTime = 'updatetime';
  13. protected $deleteTime = false;
  14. // 追加属性
  15. protected $append = [
  16. 'status_text'
  17. ];
  18. public function getStatusList()
  19. {
  20. return ['0' => __('Status 0'), '1' => __('Status 1')];
  21. }
  22. public function getStatusTextAttr($value, $data)
  23. {
  24. $value = $value ?: ($data['status'] ?? '');
  25. $list = $this->getStatusList();
  26. return $list[$value] ?? '';
  27. }
  28. /**
  29. * 添加收藏/取消收藏
  30. * @param [type] $user_id
  31. * @param [type] $goods_id
  32. * @return true
  33. */
  34. public static function addOrCancel($user_id, $goods_id)
  35. {
  36. $data = self::where('user_id', $user_id)->where('goods_id', $goods_id)->find();
  37. //不存在,添加收藏
  38. if (!$data) {
  39. return (new self)->save([
  40. 'user_id' => $user_id,
  41. 'goods_id' => $goods_id
  42. ]);
  43. }
  44. if ($data->status == 1) { //已收藏,为取消
  45. $data->status = 0;
  46. } else { //已取消,添加收藏
  47. $data->status = 1;
  48. }
  49. return $data->save();
  50. }
  51. /**
  52. * 渲染收藏
  53. *
  54. * @param [type] $list
  55. * @param [type] $user_id
  56. * @return void
  57. */
  58. public static function render($list, $user_id)
  59. {
  60. $data = self::where('user_id', $user_id)->where('status', 1)->select();
  61. $newData = [];
  62. foreach ($data as $item) {
  63. $newData[$item['goods_id']] = $item['status'];
  64. }
  65. foreach ($list as $res) {
  66. $res->isCollect = isset($newData[$res['id']]) ?? $newData[$res['id']]['status'];
  67. }
  68. }
  69. /**
  70. * 收藏列表
  71. *
  72. * @param [type] $param
  73. * @return \think\Paginator
  74. */
  75. public static function tableList($param)
  76. {
  77. $pageNum = 15;
  78. if (!empty($param['num'])) {
  79. $pageNum = $param['num'];
  80. }
  81. $list = self::with(['Goods' => function ($query) {
  82. $query->field('id,title,image,price,marketprice,description');
  83. }])
  84. ->field('id,goods_id,user_id,status,createtime')
  85. ->where(function ($query) use ($param) {
  86. $query->where('status', 1);
  87. if (!empty($param['user_id'])) {
  88. $query->where('user_id', $param['user_id']);
  89. }
  90. })->order('createtime desc')->paginate($pageNum);
  91. return $list;
  92. }
  93. public function Goods()
  94. {
  95. return $this->belongsTo('Goods', 'goods_id', 'id', [], 'LEFT');
  96. }
  97. }