Goods.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350
  1. <?php
  2. namespace app\common\model;
  3. use app\common\library\helper;
  4. use app\common\service\Goods as GoodsService;
  5. /**
  6. * 商品模型
  7. * Class Goods
  8. * @package app\common\model
  9. */
  10. class Goods extends BaseModel
  11. {
  12. protected $name = 'goods';
  13. protected $append = ['goods_sales'];
  14. /**
  15. * 计算显示销量 (初始销量 + 实际销量)
  16. * @param $value
  17. * @param $data
  18. * @return mixed
  19. */
  20. public function getGoodsSalesAttr($value, $data)
  21. {
  22. return $data['sales_initial'] + $data['sales_actual'];
  23. }
  24. /**
  25. * 获取器:单独设置折扣的配置
  26. * @param $json
  27. * @return mixed
  28. */
  29. public function getAloneGradeEquityAttr($json)
  30. {
  31. return json_decode($json, true);
  32. }
  33. /**
  34. * 修改器:单独设置折扣的配置
  35. * @param $data
  36. * @return mixed
  37. */
  38. public function setAloneGradeEquityAttr($data)
  39. {
  40. return json_encode($data);
  41. }
  42. /**
  43. * 关联商品分类表
  44. * @return \think\model\relation\BelongsTo
  45. */
  46. public function category()
  47. {
  48. return $this->belongsTo('Category');
  49. }
  50. /**
  51. * 关联商品规格表
  52. * @return \think\model\relation\HasMany
  53. */
  54. public function sku()
  55. {
  56. return $this->hasMany('GoodsSku')->order(['goods_sku_id' => 'asc']);
  57. }
  58. /**
  59. * 关联商品规格关系表
  60. * @return \think\model\relation\BelongsToMany
  61. */
  62. public function specRel()
  63. {
  64. return $this->belongsToMany('SpecValue', 'GoodsSpecRel')->order(['id' => 'asc']);
  65. }
  66. /**
  67. * 关联商品图片表
  68. * @return \think\model\relation\HasMany
  69. */
  70. public function image()
  71. {
  72. return $this->hasMany('GoodsImage')->order(['id' => 'asc']);
  73. }
  74. /**
  75. * 关联运费模板表
  76. * @return \think\model\relation\BelongsTo
  77. */
  78. public function delivery()
  79. {
  80. return $this->BelongsTo('Delivery');
  81. }
  82. /**
  83. * 关联订单评价表
  84. * @return \think\model\relation\HasMany
  85. */
  86. public function commentData()
  87. {
  88. return $this->hasMany('Comment');
  89. }
  90. /**
  91. * 计费方式
  92. * @param $value
  93. * @return mixed
  94. */
  95. public function getGoodsStatusAttr($value)
  96. {
  97. $status = [10 => '上架', 20 => '下架'];
  98. return ['text' => $status[$value], 'value' => $value];
  99. }
  100. /**
  101. * 获取商品列表
  102. * @param $param
  103. * @return mixed
  104. * @throws \think\exception\DbException
  105. */
  106. public function getList($param)
  107. {
  108. // 商品列表获取条件
  109. $params = array_merge([
  110. 'status' => 10, // 商品状态
  111. 'category_id' => 0, // 分类id
  112. 'search' => '', // 搜索关键词
  113. 'sortType' => 'all', // 排序类型
  114. 'sortPrice' => false, // 价格排序 高低
  115. 'listRows' => 15, // 每页数量
  116. ], $param);
  117. // 筛选条件
  118. $filter = [];
  119. $params['category_id'] > 0 && $filter['category_id'] = ['IN', Category::getSubCategoryId($params['category_id'])];
  120. $params['status'] > 0 && $filter['goods_status'] = $params['status'];
  121. !empty($params['search']) && $filter['goods_name'] = ['like', '%' . trim($params['search']) . '%'];
  122. // 排序规则
  123. $sort = [];
  124. if ($params['sortType'] === 'all') {
  125. $sort = ['goods_sort', 'goods_id' => 'desc'];
  126. } elseif ($params['sortType'] === 'sales') {
  127. $sort = ['goods_sales' => 'desc'];
  128. } elseif ($params['sortType'] === 'price') {
  129. $sort = $params['sortPrice'] ? ['goods_max_price' => 'desc'] : ['goods_min_price' => 'asc'];
  130. }
  131. // 商品表名称
  132. $tableName = $this->getTable();
  133. // 多规格商品 最高价与最低价
  134. $GoodsSku = new GoodsSku;
  135. $minPriceSql = $GoodsSku->field(['MIN(goods_price)'])
  136. ->where('goods_id', 'EXP', "= `$tableName`.`goods_id`")->buildSql();
  137. $maxPriceSql = $GoodsSku->field(['MAX(goods_price)'])
  138. ->where('goods_id', 'EXP', "= `$tableName`.`goods_id`")->buildSql();
  139. // 执行查询
  140. $list = $this
  141. ->field(['*', '(sales_initial + sales_actual) as goods_sales',
  142. "$minPriceSql AS goods_min_price",
  143. "$maxPriceSql AS goods_max_price"
  144. ])
  145. ->with(['category', 'image.file', 'sku'])
  146. ->where('is_delete', '=', 0)
  147. ->where($filter)
  148. ->order($sort)
  149. ->paginate($params['listRows'], false, [
  150. 'query' => \request()->request()
  151. ]);
  152. // 整理列表数据并返回
  153. return $this->setGoodsListData($list, true);
  154. }
  155. /**
  156. * 设置商品展示的数据
  157. * @param $data
  158. * @param bool $isMultiple
  159. * @param callable $callback
  160. * @return mixed
  161. */
  162. protected function setGoodsListData($data, $isMultiple = true, callable $callback = null)
  163. {
  164. if (!$isMultiple) $dataSource = [&$data]; else $dataSource = &$data;
  165. // 整理商品列表数据
  166. foreach ($dataSource as &$goods) {
  167. // 商品主图
  168. $goods['goods_image'] = $goods['image'][0]['file_path'];
  169. // 商品默认规格
  170. $goods['goods_sku'] = $goods['sku'][0];
  171. // 回调函数
  172. is_callable($callback) && call_user_func($callback, $goods);
  173. }
  174. return $data;
  175. }
  176. /**
  177. * 根据商品id集获取商品列表
  178. * @param array $goodsIds
  179. * @param null $status
  180. * @return false|\PDOStatement|string|\think\Collection
  181. * @throws \think\db\exception\DataNotFoundException
  182. * @throws \think\db\exception\ModelNotFoundException
  183. * @throws \think\exception\DbException
  184. */
  185. public function getListByIds($goodsIds, $status = null)
  186. {
  187. // 筛选条件
  188. $filter = ['goods_id' => ['in', $goodsIds]];
  189. $status > 0 && $filter['goods_status'] = $status;
  190. if (!empty($goodsIds)) {
  191. $this->orderRaw('field(goods_id, ' . implode(',', $goodsIds) . ')');
  192. }
  193. // 获取商品列表数据
  194. // ['category', 'image.file', 'sku', 'spec_rel.spec', 'delivery.rule']
  195. $data = $this->field(['content'], true)
  196. ->with(['category', 'image.file', 'sku'])
  197. ->where($filter)
  198. ->select();
  199. // 整理列表数据并返回
  200. return $this->setGoodsListData($data, true);
  201. }
  202. /**
  203. * 商品多规格信息
  204. * @param \think\Collection $specRel
  205. * @param \think\Collection $skuData
  206. * @return array
  207. */
  208. public function getManySpecData($specRel, $skuData)
  209. {
  210. // spec_attr
  211. $specAttrData = [];
  212. foreach ($specRel as $item) {
  213. if (!isset($specAttrData[$item['spec_id']])) {
  214. $specAttrData[$item['spec_id']] = [
  215. 'group_id' => $item['spec']['spec_id'],
  216. 'group_name' => $item['spec']['spec_name'],
  217. 'spec_items' => [],
  218. ];
  219. }
  220. $specAttrData[$item['spec_id']]['spec_items'][] = [
  221. 'item_id' => $item['spec_value_id'],
  222. 'spec_value' => $item['spec_value'],
  223. ];
  224. }
  225. // spec_list
  226. $specListData = [];
  227. foreach ($skuData as $item) {
  228. $image = (isset($item['image']) && !empty($item['image'])) ? $item['image'] : ['file_id' => 0, 'file_path' => ''];
  229. $specListData[] = [
  230. 'goods_sku_id' => $item['goods_sku_id'],
  231. 'spec_sku_id' => $item['spec_sku_id'],
  232. 'rows' => [],
  233. 'form' => [
  234. 'image_id' => $image['file_id'],
  235. 'image_path' => $image['file_path'],
  236. 'goods_no' => $item['goods_no'],
  237. 'goods_price' => $item['goods_price'],
  238. 'goods_weight' => $item['goods_weight'],
  239. 'line_price' => $item['line_price'],
  240. 'stock_num' => $item['stock_num'],
  241. ],
  242. ];
  243. }
  244. return ['spec_attr' => array_values($specAttrData), 'spec_list' => $specListData];
  245. }
  246. /**
  247. * 多规格表格数据
  248. * @param $goods
  249. * @return array
  250. */
  251. public function getManySpecTable(&$goods)
  252. {
  253. $specData = $this->getManySpecData($goods['spec_rel'], $goods['sku']);
  254. $totalRow = count($specData['spec_list']);
  255. foreach ($specData['spec_list'] as $i => &$sku) {
  256. $rowData = [];
  257. $rowCount = 1;
  258. foreach ($specData['spec_attr'] as $attr) {
  259. $skuValues = $attr['spec_items'];
  260. $rowCount *= count($skuValues);
  261. $anInterBankNum = ($totalRow / $rowCount);
  262. $point = (($i / $anInterBankNum) % count($skuValues));
  263. if (0 === ($i % $anInterBankNum)) {
  264. $rowData[] = [
  265. 'rowspan' => $anInterBankNum,
  266. 'item_id' => $skuValues[$point]['item_id'],
  267. 'spec_value' => $skuValues[$point]['spec_value']
  268. ];
  269. }
  270. }
  271. $sku['rows'] = $rowData;
  272. }
  273. return $specData;
  274. }
  275. /**
  276. * 获取商品详情
  277. * @param $goodsId
  278. * @return static
  279. */
  280. public static function detail($goodsId)
  281. {
  282. /* @var $model self */
  283. $model = (new static)->with([
  284. 'category',
  285. 'image.file',
  286. 'sku.image',
  287. 'spec_rel.spec',
  288. ])->where('goods_id', '=', $goodsId)
  289. ->find();
  290. if (empty($model)) {
  291. return $model;
  292. }
  293. // 整理商品数据并返回
  294. return $model->setGoodsListData($model, false);
  295. }
  296. /**
  297. * 指定的商品规格信息
  298. * @param static $goods 商品详情
  299. * @param int $specSkuId
  300. * @return array|bool
  301. */
  302. public static function getGoodsSku($goods, $specSkuId)
  303. {
  304. // 获取指定的sku
  305. $goodsSku = [];
  306. foreach ($goods['sku'] as $item) {
  307. if ($item['spec_sku_id'] == $specSkuId) {
  308. $goodsSku = $item;
  309. break;
  310. }
  311. }
  312. if (empty($goodsSku)) {
  313. return false;
  314. }
  315. // 多规格文字内容
  316. $goodsSku['goods_attr'] = '';
  317. if ($goods['spec_type'] == 20) {
  318. $specRelData = helper::arrayColumn2Key($goods['spec_rel'], 'spec_value_id');
  319. $attrs = explode('_', $goodsSku['spec_sku_id']);
  320. foreach ($attrs as $specValueId) {
  321. $goodsSku['goods_attr'] .= $specRelData[$specValueId]['spec']['spec_name'] . ':'
  322. . $specRelData[$specValueId]['spec_value'] . '; ';
  323. }
  324. }
  325. return $goodsSku;
  326. }
  327. }