| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129 |
- <?php
- namespace App\Module\Shop\Models;
- use Illuminate\Database\Eloquent\Relations\BelongsTo;
- use Illuminate\Support\Facades\DB;
- use UCore\ModelCore;
- use App\Module\GameItems\Models\Item;
- /**
- * 商店物品模型
- *
- * field start
- * @property int $id 商品ID,主键
- * @property string $name 商品名称
- * @property string $description 商品描述
- * @property int $item_id 关联的物品ID,外键关联kku_item_items表
- * @property int $item_quantity 物品数量
- * @property int $price 价格
- * @property int $currency_id 货币类型ID
- * @property int $max_buy 最大购买数量(0表示无限制)
- * @property int $is_active 是否激活(0:否, 1:是)
- * @property int $sort_order 排序权重
- * @property string $start_time 上架时间
- * @property string $end_time 下架时间
- * @property \Carbon\Carbon $created_at 创建时间
- * @property \Carbon\Carbon $updated_at 更新时间
- * field end
- */
- class ShopItem extends ModelCore
- {
- /**
- * 与模型关联的表名
- *
- * @var string
- */
- protected $table = 'shop_items';
- /**
- * 可批量赋值的属性
- *
- * @var array
- */
- protected $fillable = [
- 'name',
- 'description',
- 'item_id',
- 'item_quantity',
- 'price',
- 'currency_id',
- 'max_buy',
- 'is_active',
- 'sort_order',
- 'start_time',
- 'end_time',
- ];
- /**
- * 应该被转换为日期的属性
- *
- * @var array
- */
- protected $dates = [
- 'start_time',
- 'end_time',
- 'created_at',
- 'updated_at',
- ];
- /**
- * 应该被转换为原生类型的属性
- *
- * @var array
- */
- protected $casts = [
- 'is_active' => 'boolean',
- ];
- /**
- * 获取关联的物品
- *
- * @return BelongsTo
- */
- public function item(): BelongsTo
- {
- return $this->belongsTo(Item::class, 'item_id');
- }
- /**
- * 获取用户已购买数量
- *
- * @param int $userId 用户ID
- * @return int 已购买数量
- */
- public function getUserBoughtCount(int $userId): int
- {
- return ShopPurchaseLog::where('user_id', $userId)
- ->where('shop_item_id', $this->id)
- ->sum('quantity');
- }
- /**
- * 记录购买记录
- *
- * @param int $userId 用户ID
- * @param int $quantity 购买数量
- * @param int $totalPrice 总价
- * @return ShopPurchaseLog 购买记录
- */
- public function recordPurchase(int $userId, int $quantity, int $totalPrice): ShopPurchaseLog
- {
- $log = new ShopPurchaseLog([
- 'user_id' => $userId,
- 'shop_item_id' => $this->id,
- 'item_id' => $this->item_id,
- 'quantity' => $quantity,
- 'price' => $this->price,
- 'total_price' => $totalPrice,
- 'currency_id' => $this->currency_id,
- 'purchase_time' => now(),
- 'ip_address' => request()->ip(),
- 'device_info' => request()->userAgent(),
- ]);
-
- $log->save();
-
- return $log;
- }
- }
|