SpecValueService.php 2.1 KB

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