Shoping.php 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. <?php
  2. /**
  3. *
  4. * @copyright ©2020 点小铺
  5. * @author hanj
  6. * @link: https://dyuit.com
  7. * Created by VSCode
  8. */
  9. namespace app\common\model\wow;
  10. use app\common\model\BaseModel;
  11. /**
  12. * 好物圈商品收藏记录模型
  13. * Class Shoping
  14. * @package app\common\model\wow
  15. */
  16. class Shoping extends BaseModel
  17. {
  18. protected $name = 'wow_shoping';
  19. protected $updateTime = false;
  20. protected $alias = 'shoping';
  21. /**
  22. * 关联商品表
  23. * @return \think\model\relation\BelongsTo
  24. */
  25. public function goods()
  26. {
  27. $module = self::getCalledModule() ?: 'common';
  28. return $this->belongsTo("app\\{$module}\\model\\Goods");
  29. }
  30. /**
  31. * 关联用户表
  32. * @return \think\model\relation\BelongsTo
  33. */
  34. public function user()
  35. {
  36. $module = self::getCalledModule() ?: 'common';
  37. return $this->belongsTo("app\\{$module}\\model\\User");
  38. }
  39. /**
  40. * 获取单条记录
  41. * @param $id
  42. * @param $with
  43. * @return static|null
  44. * @throws \think\exception\DbException
  45. */
  46. public static function detail($id, $with = ['goods.image.file', 'user'])
  47. {
  48. return static::get($id, $with);
  49. }
  50. /**
  51. * 新增好物圈商品收藏记录
  52. * @param int $userId 用户id
  53. * @param array $goodsIds 商品id
  54. * @return array|false
  55. * @throws \Exception
  56. */
  57. public function add($userId, $goodsIds)
  58. {
  59. // 过滤该用户已收藏的商品id
  60. $newGoodsIds = $this->getFilterGoodsIds($userId, $goodsIds);
  61. if (empty($newGoodsIds)) {
  62. return false;
  63. }
  64. $saveData = [];
  65. foreach ($newGoodsIds as $goodsId) {
  66. $saveData[] = [
  67. 'goods_id' => $goodsId,
  68. 'user_id' => $userId,
  69. 'wxapp_id' => self::$wxapp_id,
  70. ];
  71. }
  72. return $this->isUpdate(false)->saveAll($saveData);
  73. }
  74. /**
  75. * 软删除
  76. * @return false|int
  77. */
  78. public function setDelete()
  79. {
  80. return $this->save(['is_delete' => 1]);
  81. }
  82. /**
  83. * 过滤指定用户已收藏的商品id
  84. * @param $userId
  85. * @param $newGoodsIds
  86. * @return array
  87. */
  88. private function getFilterGoodsIds($userId, $newGoodsIds)
  89. {
  90. $alreadyGoodsId = $this->where('user_id', '=', $userId)
  91. ->where('is_delete', '=', 0)
  92. ->column('goods_id');
  93. return array_diff($newGoodsIds, $alreadyGoodsId);
  94. }
  95. }