12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091 |
- <?php
- namespace App\Repositories\Models\Dwbs;
- use App\Repositories\Enums\ModelStatusEnum;
- use App\Repositories\Models\Model;
- use Illuminate\Support\Facades\Cache;
- use Illuminate\Support\Facades\DB;
- class ShopGood extends Model
- {
- /**
- * @var string
- */
- protected $table = 'dwbs_shop_goods';
- protected $guarded = [];
- /**
- * The attributes excluded from the model's JSON form.
- *
- * @var array
- */
- protected $hidden = [];
- protected $casts = [];
- public function good()
- {
- return $this->belongsTo(ShopGood::class)->select(['id', 'name', 'cover']);
- }
- public function getCoverAttribute($val)
- {
- if (empty($val)) {
- return config('app.url') . '/default/headimg.png';
- }
- return path_to_url($val);
- }
- public function setCoverAttribute($val)
- {
- $this->attributes['cover'] = url_to_path($val);
- }
- public static function byIdGetOrder($id)
- {
- return self::query()->where('id', $id)->select(['id', 'name', 'nums', 'jifen'])->where('status', ModelStatusEnum::OK)->first();
- }
- public static function updateKuCun($id, $nums)
- {
- Cache::lock("lock:shopOrder:good:{$id}")->get(function () use ($id, $nums) {
- Cache::put("model:good:nums:{$id}", $nums);
- });
- }
- public static function addGoodNums($id, $type, $add_nums)
- {
- if (!$type) {
- $add_nums = -$add_nums;
- }
- DB::beginTransaction();
- try {
- $model = self::query()->where('id', $id)->first();
- Cache::lock("lock:shopOrder:good:{$id}")->get(function () use ($id, $add_nums, $model) {
- $nums = Cache::get("model:good:nums:{$id}", $model->nums);
- $nums += $add_nums;
- if ($nums < 0) {
- $nums = 0;
- }
- Cache::put("model:good:nums:{$id}", $nums);
- $model->nums = $nums;
- $model->save();
- });
- DB::commit();
- } catch (\Exception $exception) {
- DB::rollBack();
- }
- }
- public static function reloadKuCun($good_id = 0)
- {
- $goods = self::query()->when($good_id, function ($query) use ($good_id) {
- return $query->where('id', $good_id);
- })->where('status', ModelStatusEnum::OK)->select(['id', 'nums'])->get();
- foreach ($goods as $good) {
- self::updateKuCun($good->id, $good->nums);
- }
- }
- }
|