Gift.php 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. <?php
  2. namespace app\api\model\plus\live;
  3. use app\common\enum\user\GiftLogSceneEnum;
  4. use app\common\model\plus\live\Gift as GiftModel;
  5. use app\api\model\user\User as UserModel;
  6. use app\common\model\plus\live\RoomGift as RoomGiftModel;
  7. use app\common\model\user\GiftLog as GiftLogModel;
  8. use app\common\model\plus\live\Room as RoomModel;
  9. use app\common\model\plus\live\UserGift as UserGiftModel;
  10. use app\api\model\supplier\Supplier as SupplierModel;
  11. /**
  12. * 礼物模型
  13. */
  14. class Gift extends GiftModel
  15. {
  16. /**
  17. * 获取礼物列表
  18. */
  19. public function getList()
  20. {
  21. return $this->with(['image'])
  22. ->where('is_delete', '=', 0)
  23. ->order(['sort' => 'asc', 'create_time' => 'asc'])
  24. ->select();
  25. }
  26. public function sendGift($user, $room_id, $gift_id){
  27. $gift = self::detail($gift_id);
  28. $room = RoomModel::detail($room_id);
  29. if(!$gift || $gift['is_delete'] == 1){
  30. $this->error = '礼物不存在';
  31. return false;
  32. }
  33. if($user['gift_money'] < $gift['price']){
  34. $this->error = '余额不足';
  35. return false;
  36. }
  37. $this->startTrans();
  38. try {
  39. // 扣除
  40. (new UserModel())->where('user_id', '=', $user['user_id'])
  41. ->dec('gift_money', $gift['price'])
  42. ->update();
  43. // 主播增加
  44. (new SupplierModel())->where('shop_supplier_id', '=', $room['shop_supplier_id'])
  45. ->inc('total_gift', $gift['price'])
  46. ->inc('gift_money', $gift['price'])
  47. ->update();
  48. // 房间增加
  49. (new RoomModel())->where('room_id', '=', $room_id)
  50. ->inc('gift_num', $gift['price'])
  51. ->update();
  52. // 房间用户礼物数增加
  53. $user_gift_model = UserGiftModel::detail($room_id, $user['user_id']);
  54. $user_gift_model->where('room_id', '=', $room_id)->where('user_id', '=', $user['user_id'])
  55. ->inc('gift_num', $gift['price'])->update();
  56. // 保存记录
  57. (new RoomGiftModel())->save([
  58. 'room_id' => $room_id,
  59. 'user_id' => $user['user_id'],
  60. 'shop_supplier_id' => $room['shop_supplier_id'],
  61. 'price' => $gift['price'],
  62. 'gift_name' => $gift['gift_name'],
  63. 'app_id' => self::$app_id
  64. ]);
  65. GiftLogModel::add(GiftLogSceneEnum::CONSUME, [
  66. 'user_id' => $user['user_id'],
  67. 'money' => -$gift['price'],
  68. ], ['gift_name' => $gift['gift_name']]);
  69. $this->commit();
  70. return true;
  71. } catch (\Exception $e) {
  72. $this->error = $e->getMessage();
  73. $this->rollback();
  74. return false;
  75. }
  76. }
  77. }