SpecValue.php 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  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. foreach ($valueList as $key => &$item) {
  36. $alreadyItem = helper::getArrayItemByColumn($alreadyData, 'spec_value', $item['spec_value']);
  37. if (!empty($alreadyItem)) {
  38. // 规格值已存在的记录spec_value_id
  39. $item['spec_value_id'] = $alreadyItem['spec_value_id'];
  40. } else {
  41. // 规格值不存在的新增记录
  42. $result = static::add($specId, $item);
  43. $item['spec_value_id'] = $result['spec_value_id'];
  44. }
  45. }
  46. return $valueList;
  47. }
  48. /**
  49. * 新增规格组记录
  50. * @param int $specId
  51. * @param array $item
  52. * @return Spec|\think\Model
  53. */
  54. private static function add(int $specId, array $item)
  55. {
  56. return self::create([
  57. 'spec_value' => $item['spec_value'],
  58. 'spec_id' => $specId,
  59. 'store_id' => self::$storeId
  60. ]);
  61. }
  62. /**
  63. * 根据规格组名称集获取列表
  64. * @param int $specId
  65. * @param array $values
  66. * @return \think\Collection
  67. */
  68. private static function getListByValues(int $specId, array $values)
  69. {
  70. return (new static)->where('spec_id', '=', $specId)
  71. ->where('spec_value', 'in', $values)
  72. ->select();
  73. }
  74. }