Goods.php 11 KB

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