AttributeValueService.php 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. <?php
  2. namespace addons\TinyShop\services\common;
  3. use Yii;
  4. use addons\TinyShop\common\models\common\AttributeValue;
  5. /**
  6. * Class AttributeValueService
  7. * @package addons\TinyShop\services\common
  8. */
  9. class AttributeValueService
  10. {
  11. /**
  12. * 更新数据
  13. *
  14. * @param array $data 提交的数据
  15. * @param array $oldValues 规格原先的数据
  16. * @param int $attribute_id
  17. * @param int $merchant_id
  18. * @throws \yii\db\Exception
  19. */
  20. public function updateData($data, $oldValues, $attribute_id, $merchant_id)
  21. {
  22. $allIds = [];
  23. if (isset($data['update'])) {
  24. foreach ($data['update']['id'] as $key => $datum) {
  25. if ($model = AttributeValue::findOne(['id' => $datum, 'attribute_id' => $attribute_id])) {
  26. $model->title = $data['update']['title'][$key];
  27. $model->type = $data['update']['type'][$key];
  28. $model->value = $data['update']['value'][$key];
  29. $model->sort = (int)$data['update']['sort'][$key];
  30. $model->save();
  31. $allIds[] = $model->id;
  32. }
  33. }
  34. }
  35. // 创建的内容
  36. if (isset($data['create'])) {
  37. $rows = [];
  38. foreach ($data['create']['title'] as $key => $datum) {
  39. $sort = (int)$data['create']['sort'][$key];
  40. $value = $data['create']['value'][$key];
  41. $type = $data['create']['type'][$key];
  42. $rows[] = [$merchant_id, $attribute_id, $datum, $value, $type, $sort, time(), time()];
  43. }
  44. $field = ['merchant_id', 'attribute_id', 'title', 'value', 'type', 'sort', 'created_at', 'updated_at'];
  45. !empty($rows) && Yii::$app->db->createCommand()->batchInsert(AttributeValue::tableName(), $field, $rows)->execute();
  46. }
  47. // 删除不存在的内容
  48. $deleteIds = [];
  49. foreach ($oldValues as $value) {
  50. !in_array($value['id'], $allIds) && $deleteIds[] = $value['id'];
  51. }
  52. !empty($deleteIds) && AttributeValue::deleteAll(['in', 'id', $deleteIds]);
  53. }
  54. }
粤ICP备19079148号