GoodsAttr.php 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. <?php
  2. namespace app\common\model;
  3. use think\Model;
  4. use think\Db;
  5. class GoodsAttr extends Model
  6. {
  7. // 表名
  8. protected $name = 'shop_goods_attr';
  9. // 自动写入时间戳字段
  10. protected $autoWriteTimestamp = 'int';
  11. // 定义时间戳字段名
  12. protected $createTime = 'createtime';
  13. protected $updateTime = 'updatetime';
  14. protected $deleteTime = false;
  15. // 追加属性
  16. protected $append = [];
  17. //查询符合的goods_id
  18. public static function getGoodsIds($attributes)
  19. {
  20. if (!is_array($attributes) && empty($attributes)) {
  21. return [];
  22. }
  23. $attributes = array_values($attributes);
  24. $attrSql = '';
  25. $whereSql = '1=1';
  26. foreach ($attributes as $key => $item) {
  27. $sql = self::field('goods_id')->where('attribute_id', $item['attribute_id'])->where('value_id', 'IN', $item['value_id'])->fetchSql(true)->select();
  28. if (!$key) {
  29. $attrSql .= "({$sql}) AS A{$key}";
  30. } else {
  31. $attrSql .= " INNER JOIN ({$sql}) AS A{$key}";
  32. $k = $key - 1;
  33. $whereSql .= " AND A{$k}.goods_id = A{$key}.goods_id";
  34. }
  35. }
  36. $sql = "SELECT * FROM {$attrSql} WHERE {$whereSql}";
  37. $list = Db::query($sql);
  38. return array_unique(array_column($list, 'goods_id'));
  39. $valueIds = [];
  40. foreach ($attributes as $key => $item) {
  41. $valueIds = array_merge($valueIds, explode(',', $item['value_id']));
  42. }
  43. $goodsAttrList = GoodsAttr::field('goods_id')->where('value_id', 'in', $valueIds)->column('value_id,attribute_id,goods_id');
  44. $goodsArr = [];
  45. foreach ($goodsAttrList as $index => $attr) {
  46. $goodsArr[$attr['goods_id']][$attr['attribute_id']] = $attr['value_id'];
  47. }
  48. $goodsIds = [];
  49. foreach ($goodsArr as $index => $item) {
  50. if (count($item) >= count($attributes)) {
  51. $goodsIds[] = $index;
  52. }
  53. }
  54. return array_unique($goodsIds);
  55. }
  56. }