Home  >  Q&A  >  body text

How to create products with media in Shopware 6 using Admin API?

How to create products with media using Shopware 6 Admin API PHP SDK?

Shopware 6 Management API PHP SDK

I know how to create a product using the following code snippet.

$productRepository->create([
    'id' => Uuid::randomHex(),
    'name' => 'New Product',
    'taxId' => $product->taxId,
    'price' => $product->price,
    'productNumber' => $product->productNumber . random_int(10, 1000),
    'stock' => $product->stock,
    'media' => $product->media, //Not working
], $context);

And how to upload media from a URL containing the following code snippet.

$mediaService->uploadMediaFromUrl($mediaId, $url, 'jpg', 'test-media');

But how do I add media to the product?

P粉715228019P粉715228019308 days ago453

reply all(1)I'll reply

  • P粉399090746

    P粉3990907462024-01-08 22:48:34

    media An association is a collection of product_media entities that act as a mapping to media entities. After uploading a file to create a media entity based on a URL, you can use that ID to create a product_media mapping when creating a product.

    $mediaService->uploadMediaFromUrl($mediaId1, $url, 'jpg', 'foo');
    $mediaService->uploadMediaFromUrl($mediaId2, $url, 'jpg', 'bar');
    
    $productRepository->create([
        // ...
        'media' => [
            [
                'position' => 1,
                'mediaId' => $mediaId1,
            ],
            [
                'position' => 2,
                'mediaId' => $mediaId2,
            ],
        ],
    ], $context);
    

    reply
    0
  • Cancelreply