GoodsSpecRel.php 2.8 KB

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