12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455 |
- <?php
- namespace App\Admin\Repositories;
- use App\Models\DistProductImage as Model;
- use Dcat\Admin\Repositories\EloquentRepository;
- class DistProductImage extends EloquentRepository
- {
- /**
- * Model.
- *
- * @var string
- */
- protected $eloquentClass = Model::class;
- //格式化数据,用于多图上传
- public static function formatData($productId, $images)
- {
- $existingImages = Model::where('product_id', $productId)->get();
- // 用于存储结果的数组
- $result = [];
- // 处理条件1:如果数据在 base_product_image 中有,但在 $images 上无
- foreach ($existingImages as $existingImage) {
- if (!in_array($existingImage->image_url, $images)) {
- $result[] = [
- 'id' => $existingImage->id,
- 'image_url' => $existingImage->image_url,
- '_remove_' => 1,
- ];
- }
- }
- // 处理条件2:如果数据在 base_product_image 中无,但在 $images 有
- $i = 1;
- foreach ($images as $image) {
- $found = $existingImages->firstWhere('image_url', $image);
- if (!$found) {
- $result[] = [
- 'id' => 0,
- 'image_url' => $image,
- 'order' => $i,
- ];
- }
- //更新库中排序
- foreach ($existingImages as $existingImage) {
- if ($existingImage->image_url == $image) {
- $existingImage->order = $i;
- $existingImage->save();
- }
- }
- $i++;
- }
- return $result;
- }
- }
|