GoodsSpecRel.php 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  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\common\model;
  13. /**
  14. * 商品规格关系模型
  15. * Class GoodsSpecRel
  16. * @package app\common\model
  17. */
  18. class GoodsSpecRel extends BaseModel
  19. {
  20. // 定义表名
  21. protected $name = 'goods_spec_rel';
  22. // 定义主键
  23. protected $pk = 'id';
  24. protected $updateTime = false;
  25. /**
  26. * 关联规格组
  27. * @return \think\model\relation\BelongsTo
  28. */
  29. public function spec()
  30. {
  31. return $this->belongsTo('Spec');
  32. }
  33. /**
  34. * 关联规格值
  35. * @return \think\model\relation\BelongsTo
  36. */
  37. public function specValue()
  38. {
  39. return $this->belongsTo('SpecValue');
  40. }
  41. /**
  42. * 指定商品的规格列表
  43. * @param int $goodsId 商品ID
  44. * @return array
  45. * @throws \think\db\exception\DataNotFoundException
  46. * @throws \think\db\exception\DbException
  47. * @throws \think\db\exception\ModelNotFoundException
  48. */
  49. public static function getSpecList(int $goodsId)
  50. {
  51. // 获取指定商品的规格值关系记录
  52. $data = (new static)->with(['spec', 'specValue'])
  53. ->where('goods_id', '=', $goodsId)
  54. ->select();
  55. // 规格组
  56. $groupData = [];
  57. foreach ($data as $groupKey => $item) {
  58. $groupData[$item['spec_id']] = [
  59. 'spec_id' => $item['spec']['spec_id'],
  60. 'spec_name' => $item['spec']['spec_name']
  61. ];
  62. }
  63. // 去除索引
  64. $specList = array_values($groupData);
  65. // 规格值
  66. foreach ($specList as $groupKey => &$group) {
  67. $group['key'] = $groupKey;
  68. foreach ($data as $valueKey => $item) {
  69. ($item['spec_id'] == $group['spec_id']) && $group['valueList'][] = [
  70. 'key' => isset($group['valueList']) ? count($group['valueList']) : 0,
  71. 'groupKey' => $groupKey,
  72. 'spec_value_id' => $item['specValue']['spec_value_id'],
  73. 'spec_value' => $item['specValue']['spec_value']
  74. ];
  75. }
  76. }
  77. return $specList;
  78. }
  79. }