php - Shopware 6 how create a product with media with the Admin API?

How can i create a product with media with the Shopware 6 Admin API PHP SDK ?

Shopware 6 Admin API PHP SDK

I know how to create a product with following 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 with following snippet.

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

But how can i add the media to the product ?

Answer

Solution:

The media association is a collection of product_media entities, serving as mappings to media entities. After you upload a file to create a media entity from a url, you can use that id to create product_media mappings when creating the 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);

Source