Shoping.php 2.3 KB

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