StarTrait.php 1.5KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. <?php
  2. /**
  3. * 我的关注公共助手
  4. *
  5. * @author qifan
  6. * @date 2020-12-05
  7. */
  8. namespace app\crm\traits;
  9. use think\Db;
  10. trait StarTrait
  11. {
  12. /**
  13. * 设置关注
  14. *
  15. * @param $type
  16. * @param $userId
  17. * @param $targetId
  18. * @return int|string
  19. * @throws \think\Exception
  20. * @throws \think\exception\PDOException
  21. */
  22. public function setStar($type, $userId, $targetId)
  23. {
  24. # 查询关注表里是否有数据
  25. $starId = Db::name('crm_star')->where(function ($query) use ($userId, $targetId, $type) {
  26. $query->where('user_id', $userId);
  27. $query->where('target_id', $targetId);
  28. $query->where('type', $type);
  29. })->value('star_id');
  30. # 有数据移出关注
  31. if ($starId) return $this->deleteStar($starId);
  32. # 没数据增加关注
  33. return $this->createStar($type, $userId, $targetId);
  34. }
  35. /**
  36. * 添加我的关注
  37. *
  38. * @param $type
  39. * @param $userId
  40. * @param $targetId
  41. * @return int|string
  42. */
  43. private function createStar($type, $userId, $targetId)
  44. {
  45. return Db::name('crm_star')->insert(['user_id' => $userId, 'target_id' => $targetId, 'type' => $type]);
  46. }
  47. /**
  48. * 删除我的关注
  49. *
  50. * @param $starId
  51. * @return int
  52. * @throws \think\Exception
  53. * @throws \think\exception\PDOException
  54. */
  55. private function deleteStar($starId)
  56. {
  57. return Db::name('crm_star')->where('star_id', $starId)->delete();
  58. }
  59. }