BaseProductImage.php 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  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. foreach ($images as $image) {
  54. $found = $existingImages->firstWhere('image_url', $image);
  55. if (!$found) {
  56. $result[] = [
  57. 'id' => 0,
  58. 'image_url' => $image,
  59. ];
  60. }
  61. }
  62. return $result;
  63. }
  64. }