SkuSpec.php 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. <?php
  2. namespace app\common\Service;
  3. use app\common\model\SkuSpec as SkuSpecModel;
  4. use think\Db;
  5. class SkuSpec
  6. {
  7. /**
  8. * 获取指定商品的SKU信息
  9. * @param int $goods_id 商品ID
  10. * @return array
  11. */
  12. public static function getGoodsSkuSpec($goods_id,$nType = 1)
  13. {
  14. $list = (new SkuSpecModel())
  15. ->field('MIN(`id`) AS `id`, MIN(`goods_id`) AS `goods_id`, `spec_id`')
  16. ->where('type', $nType)
  17. ->where('goods_id', $goods_id)
  18. ->with([
  19. 'Spec',
  20. 'SkuValue' => function ($query) use ($goods_id) {
  21. $query->where('goods_id', $goods_id)
  22. ->field('id,goods_id,spec_id,spec_value_id')
  23. ->with(['SpecValue']);
  24. }
  25. ])->group('spec_id')->select();
  26. $list = collection($list)->toArray();
  27. return $list;
  28. }
  29. /**
  30. * 批量获取SKU规格属性字符串
  31. * @param array $sku_ids SKU ID数组
  32. * @return array 返回 [sku_id => 'spec_name:spec_value,spec_name:spec_value'] 格式
  33. */
  34. public static function getSkuAttrs($sku_ids)
  35. {
  36. if (empty($sku_ids)) {
  37. return [];
  38. }
  39. // 通过shop_goods_sku表的spec_value_ids字段来查询规格信息
  40. $list = Db::name('shop_goods_sku')
  41. ->alias('sku')
  42. ->field('sku.id, GROUP_CONCAT(sp.name,":",sv.value ORDER BY sp.id asc) as sku_attr')
  43. ->join('shop_goods_sku_spec gss', "FIND_IN_SET(gss.id, sku.spec_value_ids)", 'LEFT')
  44. ->join('shop_spec sp', 'sp.id = gss.spec_id', 'LEFT')
  45. ->join('shop_spec_value sv', 'sv.id = gss.spec_value_id', 'LEFT')
  46. ->where('sku.id', 'in', $sku_ids)
  47. ->group('sku.id')
  48. ->select();
  49. $result = [];
  50. foreach ($list as $item) {
  51. $result[$item['id']] = $item['sku_attr'] ?: '';
  52. }
  53. return $result;
  54. }
  55. }