BaseProductImage.php 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. <?php
  2. namespace App\Admin\Repositories;
  3. use App\Models\BaseProductImage as Model;
  4. use Dcat\Admin\Repositories\EloquentRepository;
  5. use Carbon\Carbon;
  6. class BaseProductImage extends EloquentRepository
  7. {
  8. /**
  9. * Model.
  10. *
  11. * @var string
  12. */
  13. protected $eloquentClass = Model::class;
  14. public static function deleteByProductId($productId)
  15. {
  16. Model::where('product_id', $productId)->delete();
  17. }
  18. public static function saveProductImages($productId, $imageUrls)
  19. {
  20. if (empty($productId) || empty($imageUrl)) {
  21. return false;
  22. }
  23. // 准备数据集合
  24. $data = [];
  25. foreach ($imageUrls as $imageUrl) {
  26. $data[] = [
  27. 'product_id' => $productId,
  28. 'image_url' => $imageUrl,
  29. 'created_at' => Carbon::now(),
  30. 'updated_at' => Carbon::now(),
  31. ];
  32. }
  33. // 批量插入
  34. return Model::insert($data);
  35. }
  36. //格式化数据,用于多图上传
  37. public static function formatData($productId, $images)
  38. {
  39. $existingImages = Model::where('product_id', $productId)->get();
  40. // 用于存储结果的数组
  41. $result = [];
  42. // 处理条件1:如果数据在 base_product_image 中有,但在 $images 上无
  43. foreach ($existingImages as $existingImage) {
  44. if (!in_array($existingImage->image_url, $images)) {
  45. $result[] = [
  46. 'id' => $existingImage->id,
  47. 'image_url' => $existingImage->image_url,
  48. '_remove_' => 1,
  49. ];
  50. }
  51. }
  52. // 处理条件2:如果数据在 base_product_image 中无,但在 $images 有
  53. $i = 1;
  54. foreach ($images as $image) {
  55. $found = $existingImages->firstWhere('image_url', $image);
  56. if (!$found) {
  57. $result[] = [
  58. 'id' => 0,
  59. 'image_url' => $image,
  60. 'order' => $i,
  61. ];
  62. }
  63. //更新库中排序
  64. foreach ($existingImages as $existingImage) {
  65. if ($existingImage->image_url == $image) {
  66. $existingImage->order = $i;
  67. $existingImage->save();
  68. }
  69. }
  70. $i++;
  71. }
  72. return $result;
  73. }
  74. }