SkuSpec.php 1.9 KB

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