Spec.php 3.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | 萤火商城系统 [ 致力于通过产品和服务,帮助商家高效化开拓市场 ]
  4. // +----------------------------------------------------------------------
  5. // | Copyright (c) 2017~2021 https://www.yiovo.com All rights reserved.
  6. // +----------------------------------------------------------------------
  7. // | Licensed 这不是一个自由软件,不允许对程序代码以任何形式任何目的的再发行
  8. // +----------------------------------------------------------------------
  9. // | Author: 萤火科技 <admin@yiovo.com>
  10. // +----------------------------------------------------------------------
  11. declare (strict_types=1);
  12. namespace app\store\model;
  13. use app\common\library\helper;
  14. use app\common\model\Spec as SpecModel;
  15. use app\store\model\SpecValue as SpecValueModel;
  16. /**
  17. * 规格组模型
  18. * Class Spec
  19. * @package app\store\model
  20. */
  21. class Spec extends SpecModel
  22. {
  23. /**
  24. * 规格组写入数据库并生成ID集
  25. * 此时的$specList是用户端传来的
  26. * @param array $specList
  27. * @return array
  28. * @throws \think\db\exception\DataNotFoundException
  29. * @throws \think\db\exception\DbException
  30. * @throws \think\db\exception\ModelNotFoundException
  31. */
  32. public static function getNewSpecList(array $specList)
  33. {
  34. // 规格组名称合集
  35. $names = helper::getArrayColumn($specList, 'spec_name');
  36. // 获取到已存在的规格组
  37. $alreadyData = static::getListByNames($names);
  38. // 遍历整理新的规格集
  39. foreach ($specList as $key => &$item) {
  40. $alreadyItem = helper::getArrayItemByColumn($alreadyData, 'spec_name', $item['spec_name']);
  41. if (!empty($alreadyItem)) {
  42. // 规格名已存在的记录spec_id
  43. $item['spec_id'] = $alreadyItem['spec_id'];
  44. } else {
  45. // 规格名不存在的新增记录
  46. $result = static::add($item);
  47. $item['spec_id'] = (int)$result['spec_id'];
  48. }
  49. // 规格值写入数据库并生成id
  50. $item['valueList'] = SpecValueModel::getNewValueList((int)$item['spec_id'], $item['valueList']);
  51. }
  52. return $specList;
  53. }
  54. /**
  55. * 新增规格组记录
  56. * @param array $item
  57. * @return static|\think\Model
  58. */
  59. private static function add(array $item)
  60. {
  61. // 拿到所有的规格组名称集
  62. // 获取到已存在的
  63. return self::create([
  64. 'spec_name' => $item['spec_name'],
  65. 'store_id' => self::$storeId
  66. ]);
  67. }
  68. /**
  69. * 根据规格组名称集获取列表
  70. * @param array $names
  71. * @return \think\Collection
  72. * @throws \think\db\exception\DataNotFoundException
  73. * @throws \think\db\exception\DbException
  74. * @throws \think\db\exception\ModelNotFoundException
  75. */
  76. private static function getListByNames(array $names)
  77. {
  78. return (new static)->where('spec_name', 'in', $names)->select();
  79. }
  80. }