ShopGood.php 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. <?php
  2. namespace App\Repositories\Models\Dwbs;
  3. use App\Repositories\Enums\ModelStatusEnum;
  4. use App\Repositories\Models\Model;
  5. use Illuminate\Support\Facades\Cache;
  6. use Illuminate\Support\Facades\DB;
  7. class ShopGood extends Model
  8. {
  9. /**
  10. * @var string
  11. */
  12. protected $table = 'dwbs_shop_goods';
  13. protected $guarded = [];
  14. /**
  15. * The attributes excluded from the model's JSON form.
  16. *
  17. * @var array
  18. */
  19. protected $hidden = [];
  20. protected $casts = [];
  21. public function good()
  22. {
  23. return $this->belongsTo(ShopGood::class)->select(['id', 'name', 'cover']);
  24. }
  25. public function getCoverAttribute($val)
  26. {
  27. if (empty($val)) {
  28. return config('app.url') . '/default/headimg.png';
  29. }
  30. return path_to_url($val);
  31. }
  32. public function setCoverAttribute($val)
  33. {
  34. $this->attributes['cover'] = url_to_path($val);
  35. }
  36. public static function byIdGetOrder($id)
  37. {
  38. return self::query()->where('id', $id)->select(['id', 'name', 'nums', 'jifen'])->where('status', ModelStatusEnum::OK)->first();
  39. }
  40. public static function updateKuCun($id, $nums)
  41. {
  42. Cache::lock("lock:shopOrder:good:{$id}")->get(function () use ($id, $nums) {
  43. Cache::put("model:good:nums:{$id}", $nums);
  44. });
  45. }
  46. public static function addGoodNums($id, $type, $add_nums)
  47. {
  48. if (!$type) {
  49. $add_nums = -$add_nums;
  50. }
  51. DB::beginTransaction();
  52. try {
  53. $model = self::query()->where('id', $id)->first();
  54. Cache::lock("lock:shopOrder:good:{$id}")->get(function () use ($id, $add_nums, $model) {
  55. $nums = Cache::get("model:good:nums:{$id}", $model->nums);
  56. $nums += $add_nums;
  57. if ($nums < 0) {
  58. $nums = 0;
  59. }
  60. Cache::put("model:good:nums:{$id}", $nums);
  61. $model->nums = $nums;
  62. $model->save();
  63. });
  64. DB::commit();
  65. } catch (\Exception $exception) {
  66. DB::rollBack();
  67. }
  68. }
  69. public static function reloadKuCun($good_id = 0)
  70. {
  71. $goods = self::query()->when($good_id, function ($query) use ($good_id) {
  72. return $query->where('id', $good_id);
  73. })->where('status', ModelStatusEnum::OK)->select(['id', 'nums'])->get();
  74. foreach ($goods as $good) {
  75. self::updateKuCun($good->id, $good->nums);
  76. }
  77. }
  78. }