SpecValue.php 2.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  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\SpecValue as SpecValueModel;
  15. /**
  16. * 规格/属性(值)模型
  17. * Class SpecValue
  18. * @package app\store\model
  19. */
  20. class SpecValue extends SpecValueModel
  21. {
  22. /**
  23. * 规格值写入数据库并生成id
  24. * @param int $specId
  25. * @param array $valueList
  26. * @return array
  27. */
  28. public static function getNewValueList(int $specId, array $valueList)
  29. {
  30. // 规格组名称合集
  31. $values = helper::getArrayColumn($valueList, 'spec_value');
  32. // 获取到已存在的规格值
  33. $alreadyData = static::getListByValues($specId, $values);
  34. // 遍历整理新的规格集
  35. $newValueList = [];
  36. foreach ($valueList as $key => &$item) {
  37. $alreadyItem = helper::getArrayItemByColumn($alreadyData, 'spec_value', $item['spec_value']);
  38. if (!empty($alreadyItem)) {
  39. // 规格值已存在的记录spec_value_id
  40. $item['spec_value_id'] = $alreadyItem['spec_value_id'];
  41. } else {
  42. // 规格值不存在的新增记录
  43. $result = static::add($specId, $item);
  44. $item['spec_value_id'] = $result['spec_value_id'];
  45. }
  46. $newValueList[$item['key']] = $item;
  47. }
  48. return $newValueList;
  49. }
  50. /**
  51. * 新增规格组记录
  52. * @param int $specId
  53. * @param array $item
  54. * @return Spec|\think\Model
  55. */
  56. private static function add(int $specId, array $item)
  57. {
  58. return self::create([
  59. 'spec_value' => $item['spec_value'],
  60. 'spec_id' => $specId,
  61. 'store_id' => self::$storeId
  62. ]);
  63. }
  64. /**
  65. * 根据规格组名称集获取列表
  66. * @param int $specId
  67. * @param array $values
  68. * @return \think\Collection
  69. */
  70. private static function getListByValues(int $specId, array $values)
  71. {
  72. return (new static)->where('spec_id', '=', $specId)
  73. ->where('spec_value', 'in', $values)
  74. ->select();
  75. }
  76. }