getJson('products', 'iPhone'); $this->upsertProducts($products); $this->info('Done!'); } catch (ConnectionException $e) { $this->error('Error fetching data!'); dump($e); } } /** * Prepare data and update or insert into DB * todo: need validation * * @param $products * @return void */ protected function upsertProducts($products): void { foreach ($products as $product) { // remember foreign tables data $tags = $product['tags']; $reviews = $product['reviews']; $images = $product['images']; // move some subarray elements to root $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']; // remove extra data 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)); } // delete all images and create from received ProductImage::query()->where('product_id', '=', $p->id)->delete(); foreach ($images as $image) { ProductImage::create(['product_id' => $p->id, 'url' => $image]); } } } }