DistProductImage.php 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. <?php
  2. namespace App\Admin\Repositories;
  3. use App\Models\DistProductImage as Model;
  4. use Dcat\Admin\Repositories\EloquentRepository;
  5. class DistProductImage extends EloquentRepository
  6. {
  7. /**
  8. * Model.
  9. *
  10. * @var string
  11. */
  12. protected $eloquentClass = Model::class;
  13. //格式化数据,用于多图上传
  14. public static function formatData($productId, $images)
  15. {
  16. $existingImages = Model::where('product_id', $productId)->get();
  17. // 用于存储结果的数组
  18. $result = [];
  19. // 处理条件1:如果数据在 base_product_image 中有,但在 $images 上无
  20. foreach ($existingImages as $existingImage) {
  21. if (!in_array($existingImage->image_url, $images)) {
  22. $result[] = [
  23. 'id' => $existingImage->id,
  24. 'image_url' => $existingImage->image_url,
  25. '_remove_' => 1,
  26. ];
  27. }
  28. }
  29. // 处理条件2:如果数据在 base_product_image 中无,但在 $images 有
  30. $i = 1;
  31. foreach ($images as $image) {
  32. $found = $existingImages->firstWhere('image_url', $image);
  33. if (!$found) {
  34. $result[] = [
  35. 'id' => 0,
  36. 'image_url' => $image,
  37. 'order' => $i,
  38. ];
  39. }
  40. //更新库中排序
  41. foreach ($existingImages as $existingImage) {
  42. if ($existingImage->image_url == $image) {
  43. $existingImage->order = $i;
  44. $existingImage->save();
  45. }
  46. }
  47. $i++;
  48. }
  49. return $result;
  50. }
  51. }