Goods.php 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637
  1. <?php
  2. namespace app\admin\controller\shopro\goods;
  3. use app\admin\model\shopro\activity\Activity;
  4. use app\common\controller\Backend;
  5. use think\Db;
  6. use think\exception\PDOException;
  7. use think\exception\ValidateException;
  8. use Exception;
  9. use addons\shopro\library\traits\StockWarning;
  10. /**
  11. * 商品
  12. *
  13. * @icon fa fa-circle-o
  14. */
  15. class Goods extends Backend
  16. {
  17. use StockWarning;
  18. /**
  19. * Goods模型对象
  20. * @var \app\admin\model\shopro\goods\Goods
  21. */
  22. protected $model = null;
  23. public function _initialize()
  24. {
  25. parent::_initialize();
  26. $this->model = new \app\admin\model\shopro\goods\Goods;
  27. $this->view->assign("typeList", $this->model->getTypeList());
  28. $this->view->assign("statusList", $this->model->getStatusList());
  29. $this->view->assign("dispatchTypeList", $this->model->getDispatchTypeList());
  30. }
  31. /**
  32. * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
  33. * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
  34. * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
  35. */
  36. /**
  37. * 查看
  38. */
  39. public function index()
  40. {
  41. //当前是否为关联查询
  42. $this->relationSearch = false;
  43. //设置过滤方法
  44. $this->request->filter(['strip_tags', 'trim']);
  45. if ($this->request->isAjax()) {
  46. //如果发送的来源是Selectpage,则转发到Selectpage
  47. if ($this->request->request('keyField')) {
  48. return $this->selectpage();
  49. }
  50. // list($where, $sort, $order, $offset, $limit) = $this->buildparams('title');
  51. $sort = $this->request->get("sort", !empty($this->model) && $this->model->getPk() ? $this->model->getPk() : 'id');
  52. $sort = $sort == 'price' ? 'convert(`price`, DECIMAL(10, 2))' : $sort;
  53. $order = $this->request->get("order", "DESC");
  54. $offset = $this->request->get("offset", 0);
  55. $limit = $this->request->get("limit", 0);
  56. $activity_type = $this->request->get("activity_type", 'all'); // 活动类型
  57. $total = $this->buildSearchOrder()->count();
  58. // 构建查询数据条件
  59. $list = $this->buildSearchOrder();
  60. $subsql = \app\admin\model\shopro\goods\SkuPrice::where('status', 'up')->field('sum(stock) as stock, goods_id as sku_goods_id')->group('goods_id')->buildSql();
  61. $goodsTableName = $this->model->getQuery()->getTable();
  62. // 关联规格表,获取总库存
  63. $list = $list->join([$subsql => 'w'], $goodsTableName . '.id = w.sku_goods_id', 'left');
  64. // 关联查询当前商品的活动,一个商品可能存在多条活动记录,使用 group_concat 搜集所有活动类型,关联条件 只有 find_in_set 会存在一个商品出现多次,所以使用 group
  65. $actSubSql = \app\admin\model\shopro\activity\Activity::where('starttime', '<=', time())->where('endtime', '>=', time())->buildSql();
  66. $list = $list->join([$actSubSql => 'act'], "(find_in_set(" . $goodsTableName . ".id, act.goods_ids) or act.goods_ids = '')", 'left');
  67. // 关联查询当前商品是否设置有积分
  68. $scoreSubSql = \app\admin\model\shopro\app\ScoreSkuPrice::field("'score' as app_type, goods_id as score_goods_id")->group('score_goods_id')->buildSql();
  69. $list = $list->join([$scoreSubSql => 'score'], $goodsTableName . '.id = score.score_goods_id', 'left');
  70. // 关闭 sql mode 的 ONLY_FULL_GROUP_BY
  71. $oldModes = closeStrict(['ONLY_FULL_GROUP_BY']);
  72. $list = $list->field("$goodsTableName.*, w.*,score.*,group_concat(act.type) as activity_type, act.goods_ids")
  73. ->group('id')
  74. ->orderRaw($sort . ' ' . $order)
  75. ->limit($offset, $limit)
  76. ->select();
  77. // 恢复 sql mode
  78. recoverStrict($oldModes);
  79. foreach ($list as $row) {
  80. $row->visible(['id', 'type', 'activity_id', 'activity_type', 'is_sku', 'app_type', 'title', 'status', 'weigh', 'category_ids', 'image', 'price', 'likes', 'views', 'sales', 'stock', 'show_sales', 'dispatch_type', 'updatetime']);
  81. }
  82. $list = collection($list)->toArray();
  83. $result = array("total" => $total, "rows" => $list);
  84. if ($this->request->get("page_type") == 'select') {
  85. return json($result);
  86. }
  87. return $this->success('操作成功', null, $result);
  88. }
  89. return $this->view->fetch();
  90. }
  91. /**
  92. * 添加
  93. */
  94. public function add()
  95. {
  96. if ($this->request->isPost()) {
  97. $params = $this->request->post("row/a");
  98. $sku = $this->request->post("sku/a");
  99. if ($params) {
  100. $params = $this->preExcludeFields($params);
  101. if (!$params['is_sku']) {
  102. // 单规格,price 必须是数字
  103. if (!preg_match('/^[0-9]+(.[0-9]{1,8})?$/', $params['price'])) {
  104. $this->error("请填写正确的价格");
  105. }
  106. }
  107. if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
  108. $params[$this->dataLimitField] = $this->auth->id;
  109. }
  110. $result = false;
  111. Db::startTrans();
  112. try {
  113. $result = $this->model->validateFailException(true)->validate('\app\admin\validate\shopro\Goods.add')->allowField(true)->save($params);
  114. if ($result) {
  115. $this->editSku($this->model, $sku, 'add');
  116. Db::commit();
  117. }
  118. } catch (ValidateException $e) {
  119. Db::rollback();
  120. $this->error($e->getMessage());
  121. } catch (PDOException $e) {
  122. Db::rollback();
  123. $this->error($e->getMessage());
  124. } catch (Exception $e) {
  125. Db::rollback();
  126. $this->error($e->getMessage());
  127. }
  128. if ($result !== false) {
  129. $this->success("添加成功");
  130. } else {
  131. $this->error(__('No rows were inserted'));
  132. }
  133. }
  134. $this->error(__('Parameter %s can not be empty', ''));
  135. }
  136. return $this->view->fetch();
  137. }
  138. /**
  139. * 查看详情
  140. */
  141. public function detail($ids = null) {
  142. $row = $this->model->get($ids);
  143. if (!$row) {
  144. $this->error(__('No Results were found'));
  145. }
  146. $row->append(['category_ids_arr', 'params_arr', 'dispatch_group_ids_arr']);
  147. $result = [];
  148. if ($row['is_sku']) {
  149. $skuList = \app\admin\model\shopro\goods\Sku::all(['pid' => 0, 'goods_id' => $ids]);
  150. if ($skuList) {
  151. foreach ($skuList as &$s) {
  152. $s->children = \app\admin\model\shopro\goods\Sku::all(['pid' => $s->id, 'goods_id' => $ids]);
  153. }
  154. }
  155. $result['skuList'] = $skuList;
  156. $skuPrice = \app\admin\model\shopro\goods\SkuPrice::all(['goods_id' => $ids]);
  157. $result['skuPrice'] = $skuPrice;
  158. } else {
  159. // 将单规格的部分数据直接放到 row 上
  160. $goodsSkuPrice = \app\admin\model\shopro\goods\SkuPrice::where('goods_id', $ids)->order('id', 'asc')->find();
  161. $row['stock'] = $goodsSkuPrice['stock'] ?? 0;
  162. $row['sn'] = $goodsSkuPrice['sn'] ?? "";
  163. $row['weight'] = $goodsSkuPrice['weight'] ?? 0;
  164. $row['stock_warning'] = $goodsSkuPrice['stock_warning'];
  165. $result['skuList'] = [];
  166. $result['skuPrice'] = [];
  167. }
  168. $result['detail'] = $row;
  169. return $this->success('获取成功', null, $result);
  170. }
  171. /**
  172. * 编辑
  173. */
  174. public function edit($ids = null)
  175. {
  176. if(!$ids) {
  177. $ids = $this->request->get('id');
  178. }
  179. $row = $this->model->get($ids);
  180. if (!$row) {
  181. $this->error(__('No Results were found'));
  182. }
  183. $row->updatetime = time();
  184. $adminIds = $this->getDataLimitAdminIds();
  185. if (is_array($adminIds)) {
  186. if (!in_array($row[$this->dataLimitField], $adminIds)) {
  187. $this->error(__('You have no permission'));
  188. }
  189. }
  190. if ($this->request->isPost()) {
  191. $params = $this->request->post("row/a");
  192. $sku = $this->request->post("sku/a");
  193. if ($params) {
  194. $this->excludeFields = ['is_sku', 'type'];
  195. $params = $this->preExcludeFields($params);
  196. $result = false;
  197. Db::startTrans();
  198. try {
  199. $result = $row->validateFailException(true)->validate('\app\admin\validate\shopro\Goods.edit')->allowField(true)->save($params);
  200. if ($result) {
  201. $this->editSku($row, $sku, 'edit');
  202. Db::commit();
  203. }
  204. } catch (ValidateException $e) {
  205. Db::rollback();
  206. $this->error($e->getMessage());
  207. } catch (PDOException $e) {
  208. Db::rollback();
  209. $this->error($e->getMessage());
  210. } catch (Exception $e) {
  211. Db::rollback();
  212. $this->error($e->getMessage());
  213. }
  214. if ($result !== false) {
  215. $this->success("编辑成功");
  216. } else {
  217. $this->error(__('No rows were updated'));
  218. }
  219. }
  220. $this->error(__('Parameter %s can not be empty', ''));
  221. }
  222. $this->view->assign("row", $row);
  223. $skuList = \app\admin\model\shopro\goods\Sku::all(['pid' => 0, 'goods_id' => $ids]);
  224. if ($skuList) {
  225. foreach ($skuList as &$s) {
  226. $s->children = \app\admin\model\shopro\goods\Sku::all(['pid' => $s->id, 'goods_id' => $ids]);
  227. }
  228. }
  229. $this->assignconfig('skuList', $skuList);
  230. $skuPrice = \app\admin\model\shopro\goods\SkuPrice::all(['goods_id' => $ids]);
  231. $this->assignconfig('skuPrice', $skuPrice);
  232. return $this->view->fetch();
  233. }
  234. public function select()
  235. {
  236. if ($this->request->isAjax()) {
  237. return $this->index();
  238. }
  239. $categoryModel = new \app\admin\model\shopro\Category;
  240. $category = $categoryModel->with('children.children.children')->where('pid', 0)->order('weigh desc, id asc')->select();
  241. $this->assignconfig('category', $category);
  242. return $this->view->fetch();
  243. }
  244. public function setStatus($ids, $status) {
  245. if ($ids) {
  246. $pk = $this->model->getPk();
  247. $adminIds = $this->getDataLimitAdminIds();
  248. if (is_array($adminIds)) {
  249. $this->model->where($this->dataLimitField, 'in', $adminIds);
  250. }
  251. $list = $this->model->where($pk, 'in', $ids)->select();
  252. $count = 0;
  253. Db::startTrans();
  254. try {
  255. foreach ($list as $k => $v) {
  256. $v->status = $status;
  257. $count += $v->save();
  258. }
  259. Db::commit();
  260. } catch (PDOException $e) {
  261. Db::rollback();
  262. $this->error($e->getMessage());
  263. } catch (Exception $e) {
  264. Db::rollback();
  265. $this->error($e->getMessage());
  266. }
  267. if ($count) {
  268. $this->success();
  269. } else {
  270. $this->error(__('No rows were updated'));
  271. }
  272. }
  273. $this->error(__('Parameter %s can not be empty', 'ids'));
  274. }
  275. protected function editSku($goods, $sku, $type = 'add')
  276. {
  277. if ($goods['is_sku']) {
  278. // 多规格
  279. $this->editMultSku($goods, $sku, $type);
  280. } else {
  281. $this->editSimSku($goods, $sku, $type);
  282. }
  283. }
  284. /**
  285. * 添加编辑单规格
  286. */
  287. protected function editSimSku($goods, $sku, $type = 'add') {
  288. $params = $this->request->post("row/a");
  289. $data = [
  290. "goods_id" => $goods['id'],
  291. "stock" => $params['stock'] ?? 0,
  292. "stock_warning" => isset($params['stock_warning']) && is_numeric($params['stock_warning'])
  293. ? $params['stock_warning'] : null,
  294. "sn" => $params['sn'] ?? "",
  295. "weight" => $params['weight'] ? intval($params['weight']) : 0,
  296. "price" => $params['price'] ?? 0,
  297. "status" => 'up'
  298. ];
  299. if ($type == 'add') {
  300. $goodsSkuPrice = new \app\admin\model\shopro\goods\SkuPrice();
  301. } else {
  302. // 查询
  303. $goodsSkuPrice = \app\admin\model\shopro\goods\SkuPrice::where('goods_id', $goods['id'])->order('id', 'asc')->find();
  304. if (!$goodsSkuPrice) {
  305. $goodsSkuPrice = new \app\admin\model\shopro\goods\SkuPrice();
  306. }
  307. }
  308. $goodsSkuPrice->save($data);
  309. // 检测库存预警
  310. $this->checkStockWarning($goodsSkuPrice);
  311. }
  312. /**
  313. * 添加编辑多规格
  314. */
  315. protected function editMultSku($goods, $sku, $type = 'add') {
  316. $skuList = json_decode($sku['listData'], true);
  317. $skuPrice = json_decode($sku['priceData'], true);
  318. if (count($skuList) < 1) {
  319. throw Exception('请填写规格列表');
  320. }
  321. foreach ($skuList as $key => $sku) {
  322. if (count($sku['children']) <= 0) {
  323. throw Exception('主规格至少要有一个子规格');
  324. }
  325. // 验证子规格不能为空
  326. foreach ($sku['children'] as $k => $child) {
  327. if (!isset($child['name']) || empty(trim($child['name']))) {
  328. throw Exception('子规格不能为空');
  329. }
  330. }
  331. }
  332. if (count($skuPrice) < 1) {
  333. throw Exception('请填写规格价格');
  334. }
  335. foreach ($skuPrice as &$price) {
  336. if (empty($price['price']) || $price['price'] == 0) {
  337. throw Exception('请填写规格价格');
  338. }
  339. if ($price['stock'] === '') {
  340. throw Exception('请填写规格库存');
  341. }
  342. if (empty($price['weight'])) {
  343. $price['weight'] = 0;
  344. }
  345. }
  346. // 编辑保存规格项
  347. $allChildrenSku = $this->saveSkuList($goods, $skuList, $type);
  348. if ($type == 'add') {
  349. // 创建新产品,添加规格列表和规格价格
  350. foreach ($skuPrice as $s3 => &$k3) {
  351. $k3['goods_sku_ids'] = $this->checkRealIds($k3['goods_sku_temp_ids'], $allChildrenSku);
  352. $k3['goods_id'] = $goods->id;
  353. $k3['goods_sku_text'] = implode(',', $k3['goods_sku_text']);
  354. $k3['weight'] = intval($k3['weight']);
  355. $k3['createtime'] = time();
  356. $k3['updatetime'] = time();
  357. unset($k3['id']);
  358. unset($k3['temp_id']); // 前端临时 id
  359. unset($k3['goods_sku_temp_ids']); // 前端临时规格 id,查找真实 id 用
  360. }
  361. $res = (new \app\admin\model\shopro\goods\SkuPrice)->allowField(true)->saveAll($skuPrice);
  362. // 检测库存预警
  363. $this->checkAllStockWarning($res, 'add');
  364. } else {
  365. // 编辑旧商品,先删除老的不用的 skuPrice
  366. $oldSkuPriceIds = array_column($skuPrice, 'id');
  367. // 删除当前商品老的除了在基础上修改的skuPrice
  368. \app\admin\model\shopro\goods\SkuPrice::where('goods_id', $goods->id)
  369. ->where('id', 'not in', $oldSkuPriceIds)->delete();
  370. // 删除失效的库存预警记录
  371. $this->delNotStockWarning($oldSkuPriceIds, $goods->id);
  372. foreach ($skuPrice as $s3 => &$k3) {
  373. $data['goods_sku_ids'] = $this->checkRealIds($k3['goods_sku_temp_ids'], $allChildrenSku);
  374. $data['goods_id'] = $goods->id;
  375. $data['goods_sku_text'] = implode(',', $k3['goods_sku_text']);
  376. $data['weigh'] = $k3['weigh'];
  377. $data['image'] = $k3['image'];
  378. $data['stock'] = $k3['stock'];
  379. $data['stock_warning'] = $k3['stock_warning'];
  380. $data['sn'] = $k3['sn'];
  381. $data['weight'] = intval($k3['weight']);
  382. $data['price'] = $k3['price'];
  383. $data['status'] = $k3['status'];
  384. $data['createtime'] = time();
  385. $data['updatetime'] = time();
  386. if ($k3['id']) {
  387. // 编辑
  388. $goodsSkuPrice = \app\admin\model\shopro\goods\SkuPrice::get($k3['id']);
  389. } else {
  390. // 新增数据
  391. $goodsSkuPrice = new \app\admin\model\shopro\goods\SkuPrice();
  392. }
  393. if ($goodsSkuPrice) {
  394. $goodsSkuPrice->save($data);
  395. // 检测库存预警
  396. $this->checkStockWarning($goodsSkuPrice);
  397. }
  398. }
  399. }
  400. }
  401. // 根据前端临时 temp_id 获取真实的数据库 id
  402. private function checkRealIds($newGoodsSkuIds, $allChildrenSku)
  403. {
  404. $newIdsArray = [];
  405. foreach ($newGoodsSkuIds as $id) {
  406. $newIdsArray[] = $allChildrenSku[$id];
  407. }
  408. return implode(',', $newIdsArray);
  409. }
  410. // 差异更新 规格规格项(多的删除,少的添加)
  411. private function saveSkuList($goods, $skuList, $type = 'add') {
  412. $allChildrenSku = [];
  413. if ($type == 'edit') {
  414. // 删除无用老规格
  415. // 拿出需要更新的老规格
  416. $oldSkuIds = [];
  417. foreach ($skuList as $key => $sku) {
  418. $oldSkuIds[] = $sku['id'];
  419. $childSkuIds = [];
  420. if ($sku['children']) {
  421. // 子项 id
  422. $childSkuIds = array_column($sku['children'], 'id');
  423. }
  424. $oldSkuIds = array_merge($oldSkuIds, $childSkuIds);
  425. $oldSkuIds = array_unique($oldSkuIds);
  426. }
  427. // 删除老的除了在基础上修改的规格项
  428. \app\admin\model\shopro\goods\Sku::where('goods_id', $goods->id)->where('id', 'not in', $oldSkuIds)->delete();
  429. }
  430. foreach ($skuList as $s1 => &$k1) {
  431. //添加主规格
  432. if ($k1['id']) {
  433. // 编辑
  434. \app\admin\model\shopro\goods\Sku::where('id', $k1['id'])->update([
  435. 'name' => $k1['name'],
  436. ]);
  437. $skuId[$s1] = $k1['id'];
  438. } else {
  439. // 新增
  440. $skuId[$s1] = \app\admin\model\shopro\goods\Sku::insertGetId([
  441. 'name' => $k1['name'],
  442. 'pid' => 0,
  443. 'goods_id' => $goods->id
  444. ]);
  445. }
  446. $k1['id'] = $skuId[$s1];
  447. foreach ($k1['children'] as $s2 => &$k2) {
  448. if ($k2['id']) {
  449. // 编辑
  450. \app\admin\model\shopro\goods\Sku::where('id', $k2['id'])->update([
  451. 'name' => $k2['name'],
  452. ]);
  453. $skuChildrenId[$s1][$s2] = $k2['id'];
  454. } else {
  455. $skuChildrenId[$s1][$s2] = \app\admin\model\shopro\goods\Sku::insertGetId([
  456. 'name' => $k2['name'],
  457. 'pid' => $k1['id'],
  458. 'goods_id' => $goods->id
  459. ]);
  460. }
  461. $allChildrenSku[$k2['temp_id']] = $skuChildrenId[$s1][$s2];
  462. $k2['id'] = $skuChildrenId[$s1][$s2];
  463. $k2['pid'] = $k1['id'];
  464. }
  465. }
  466. return $allChildrenSku;
  467. }
  468. // 构建查询条件
  469. private function buildSearchOrder()
  470. {
  471. $search = $this->request->get("search", ''); // 关键字
  472. $status = $this->request->get("status", 'all');
  473. $activity_type = $this->request->get("activity_type", 'all');
  474. $app_type = $this->request->get("app_type", 'all');
  475. $min_price = $this->request->get("min_price", "");
  476. $max_price = $this->request->get("max_price", "");
  477. $category_id = $this->request->get('category_id', 0);
  478. $name = $this->model->getQuery()->getTable();
  479. $tableName = $name . '.';
  480. $goods = $this->model;
  481. if ($search) {
  482. // 模糊搜索字段
  483. $searcharr = ['title', 'id'];
  484. foreach ($searcharr as $k => &$v) {
  485. $v = stripos($v, ".") === false ? $tableName . $v : $v;
  486. }
  487. unset($v);
  488. $goods = $goods->where(function ($query) use ($searcharr, $search, $tableName) {
  489. $query->where(implode("|", $searcharr), "LIKE", "%{$search}%");
  490. });
  491. }
  492. $goods_ids = [];
  493. // 活动
  494. if ($activity_type != 'all') {
  495. // 同一请求,会组装两次请求条件,缓存 10 秒
  496. $activities = Activity::cache(10)->where('type', $activity_type)->column('goods_ids');
  497. foreach ($activities as $key => $goods_id) {
  498. $ids = explode(',', $goods_id);
  499. $goods_ids = array_merge($goods_ids, $ids);
  500. }
  501. }
  502. // 积分
  503. if ($app_type == 'score') {
  504. $score_goods_ids = \app\admin\model\shopro\app\ScoreSkuPrice::cache(10)->group('goods_id')->column('goods_id');
  505. $goods_ids = array_merge($goods_ids, $score_goods_ids);
  506. }
  507. $goods_ids = array_filter(array_unique($goods_ids));
  508. if ($goods_ids) {
  509. $goods = $goods->where($tableName . 'id', 'in', $goods_ids);
  510. } else {
  511. if ($activity_type != 'all' || $app_type != 'all') {
  512. // 搜了活动,但是 goods_ids 为空,这时候搜索结果应该为空
  513. $goods = $goods->where($tableName . 'id', 'in', $goods_ids);
  514. }
  515. }
  516. // 价格
  517. if ($min_price != '') {
  518. $goods = $goods->where('convert(`price`, DECIMAL(10, 2)) >= ' . round($min_price, 2));
  519. }
  520. if ($max_price != '') {
  521. $goods = $goods->where('convert(`price`, DECIMAL(10, 2)) <= ' . round($max_price, 2));
  522. }
  523. // 商品状态
  524. if ($status != 'all') {
  525. $goods = $goods->where('status', 'in', $status);
  526. }
  527. if(isset($category_id) && $category_id != 0) {
  528. $category_ids = [];
  529. // 查询分类所有子分类,包括自己
  530. $category_ids = \addons\shopro\model\Category::getCategoryIds($category_id);
  531. $goods = $goods->where(function ($query) use ($category_ids) {
  532. // 所有子分类使用 find_in_set or 匹配,亲测速度并不慢
  533. foreach($category_ids as $key => $category_id) {
  534. $query->whereOrRaw("find_in_set($category_id, category_ids)");
  535. }
  536. });
  537. }
  538. return $goods;
  539. }
  540. }