SkuSpec.php 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  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('goods_id', $goods_id)
  17. ->with([
  18. 'Spec' => function ($query) use ($nType) {
  19. $query->where('type', $nType);
  20. },
  21. 'SkuValue' => function ($query) use ($goods_id) {
  22. $query->where('goods_id', $goods_id)
  23. ->field('id,goods_id,spec_id,spec_value_id')
  24. ->with(['SpecValue']);
  25. }
  26. ])->group('spec_id')->select();
  27. $list = collection($list)->toArray();
  28. return $list;
  29. }
  30. /**
  31. * 批量获取SKU规格属性字符串
  32. * @param array $sku_ids SKU ID数组
  33. * @return array 返回 [sku_id => 'spec_name:spec_value,spec_name:spec_value'] 格式
  34. */
  35. public static function getSkuAttrs($sku_ids)
  36. {
  37. if (empty($sku_ids)) {
  38. return [];
  39. }
  40. // 通过shop_goods_sku表的spec_value_ids字段来查询规格信息
  41. $list = Db::name('shop_goods_sku')
  42. ->alias('sku')
  43. ->field('sku.id, GROUP_CONCAT(sp.name,":",sv.value ORDER BY sp.id asc) as sku_attr')
  44. ->join('shop_goods_sku_spec gss', "FIND_IN_SET(gss.id, sku.spec_value_ids)", 'LEFT')
  45. ->join('shop_spec sp', 'sp.id = gss.spec_id', 'LEFT')
  46. ->join('shop_spec_value sv', 'sv.id = gss.spec_value_id', 'LEFT')
  47. ->where('sku.id', 'in', $sku_ids)
  48. ->group('sku.id')
  49. ->select();
  50. $result = [];
  51. foreach ($list as $item) {
  52. $result[$item['id']] = $item['sku_attr'] ?: '';
  53. }
  54. return $result;
  55. }
  56. }