// +---------------------------------------------------------------------- declare (strict_types=1); namespace app\common\model\sharp; use cores\BaseModel; use app\common\service\Goods as GoodsService; use think\model\relation\BelongsTo; use think\model\relation\HasMany; /** * 整点秒杀-商品模型 * Class Goods * @package app\common\model\sharp */ class Goods extends BaseModel { // 定义表名 protected $name = 'sharp_goods'; // 定义主键 protected $pk = 'sharp_goods_id'; // 定义别名 protected string $alias = 'sharp_goods'; /** * 关联商品表 * @return BelongsTo */ public function goods(): BelongsTo { $module = self::getCalledModule(); return $this->belongsTo("app\\{$module}\\model\\Goods", 'goods_id'); } /** * 关联商品规格表 * @return HasMany */ public function skuList(): HasMany { return $this->hasMany('GoodsSku', 'sharp_goods_id')->order(['id' => 'asc']); } /** * 根据秒杀商品ID集获取商品列表 * @param array $goodsIds 秒杀商品ID集 * @param array $param 查询参数 * @return mixed|\think\Paginator * @throws \think\db\exception\DbException */ public function getListByIds(array $goodsIds, array $param = []) { // 默认查询条件 $params = $this->setQueryDefaultValue($param, [ 'status' => null, 'limit' => 15, ]); // 检索查询条件 $filter = []; // 筛选条件 !is_null($params['status']) && $filter[] = ['status', '=', (int)$params['status']]; // 获取商品列表数据 $list = $this->where($filter) ->where('sharp_goods_id', 'in', $goodsIds) ->where('is_delete', '=', 0) ->order(['sort' => 'asc']) ->paginate($params['limit']); // 设置商品数据 return !$list->isEmpty() ? $this->setGoodsListData($list, true) : $list; } /** * 秒杀商品详情 * @param int $sharpGoodsId * @param array $with * @return static|array|null */ public static function detail(int $sharpGoodsId, array $with = []) { return static::get($sharpGoodsId, $with); } /** * 设置商品展示的数据 * @param $data * @param bool $isMultiple * @param callable|null $callback * @return mixed */ protected function setGoodsListData($data, bool $isMultiple = true, callable $callback = null) { // 设置主商品数据 $data = GoodsService::setGoodsData($data, $isMultiple, ['goods_images']); if (!$isMultiple) $dataSource = [&$data]; else $dataSource = &$data; // 整理商品数据 foreach ($dataSource as &$item) { // 商品名称 $item['goods_name'] = $item['goods']['goods_name']; // 商品图片 $item['goods_image'] = $item['goods']['goods_image']; // 秒杀商品原价 (获取主商品价格) $item['original_price'] = $item['goods']['goods_price_min']; // 回调函数 is_callable($callback) && call_user_func($callback, $item); } return $data; } }