Alexander Musikhin 1 год назад
Родитель
Сommit
85cab1a5c2
1 измененных файлов с 43 добавлено и 1 удалено
  1. 43 1
      app/Console/Commands/GetProducts.php

+ 43 - 1
app/Console/Commands/GetProducts.php

@@ -3,6 +3,9 @@
 namespace App\Console\Commands;
 
 use App\Models\Product;
+use App\Models\ProductImage;
+use App\Models\ProductReview;
+use App\Models\Tag;
 use Illuminate\Console\Command;
 use Illuminate\Support\Facades\Http;
 use Illuminate\Support\Str;
@@ -60,11 +63,50 @@ class GetProducts extends Command
         foreach ($products as $product){
 
             $tags = $product['tags'];
-//            $reviews =
+            $reviews = $product['reviews'];
+            $images = $product['images'];
+
+            $product['width'] = $product['dimensions']['width'];
+            $product['height'] = $product['dimensions']['height'];
+            $product['depth'] = $product['dimensions']['depth'];
+            $product['barcode'] = $product['meta']['barcode'];
+            $product['qr_code'] = $product['meta']['qrCode'];
+
+            unset($product['tags'], $product['reviews'], $product['images'], $product['dimensions'], $product['meta'] );
+
 
             $product = $this->arrayKeysCamelToSnake($product);
             Product::query()->updateOrInsert(['id' => $product['id']], $product);
+            $p = Product::find($product['id']);
+
+            // detach all tags and attach received
+            $p->tags()->detach();
+            $p->tags()->attach($this->getTagsIds($tags));
+
+            // delete all reviews and create from received
+            ProductReview::query()->where('product_id', '=', $p->id)->delete();
+            foreach ($reviews as $review){
+                $review['product_id'] = $p->id;
+                ProductReview::query()->create($this->arrayKeysCamelToSnake($review));
+            }
+
+            ProductImage::query()->where('product_id', '=', $p->id)->delete();
+            foreach ($images as $image){
+                ProductImage::create(['product_id' => $p->id, 'url' => $image]);
+            }
+
+
+        }
+    }
+
+    protected function getTagsIds($tags):array
+    {
+        $ids = [];
+        foreach ($tags as $tag){
+            $t = Tag::query()->firstOrCreate(['name' => $tag]);
+            $ids[] = $t->id;
         }
+        return $ids;
     }
 
     protected function arrayKeysCamelToSnake($arr): array