Magento 2 Documentation  2.3
Documentation for Magento 2 CMS v2.3 (December 2018)
categories_with_products.php
Go to the documentation of this file.
1 <?php
9  \Magento\Catalog\Setup\CategorySetup::class
10 );
11 require __DIR__ . '/categories.php';
12 
14 $productRepository = $objectManager->create(\Magento\Catalog\Api\ProductRepositoryInterface::class);
16  \Magento\Catalog\Api\CategoryLinkRepositoryInterface::class,
17  [
18  'productRepository' => $productRepository
19  ]
20 );
21 
24  \Magento\Catalog\Api\CategoryLinkManagementInterface::class,
25  [
26  'productRepository' => $productRepository,
27  'categoryLinkRepository' => $categoryLinkRepository
28  ]
29 );
30 
33 $product->setTypeId(\Magento\Catalog\Model\Product\Type::TYPE_SIMPLE)
34  ->setAttributeSetId($installer->getAttributeSetId('catalog_product', 'Default'))
35  ->setStoreId(1)
36  ->setWebsiteIds([1])
37  ->setName('Simple Product')
38  ->setSku('simple')
39  ->setPrice(10)
40  ->setWeight(18)
41  ->setStockData(['use_config_manage_stock' => 0])
42  ->setVisibility(\Magento\Catalog\Model\Product\Visibility::VISIBILITY_BOTH)
43  ->setStatus(\Magento\Catalog\Model\Product\Attribute\Source\Status::STATUS_ENABLED)
44  ->save();
45 $categoryLinkManagement->assignProductToCategories($product->getSku(), [2, 3, 4]);
46 
47 $product = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->create(\Magento\Catalog\Model\Product::class);
48 $product->setTypeId(\Magento\Catalog\Model\Product\Type::TYPE_SIMPLE)
49  ->setAttributeSetId($installer->getAttributeSetId('catalog_product', 'Default'))
50  ->setStoreId(1)
51  ->setWebsiteIds([1])
52  ->setName('Simple Product Two')
53  ->setSku('12345') // SKU intentionally contains digits only
54  ->setPrice(45.67)
55  ->setWeight(56)
56  ->setStockData(['use_config_manage_stock' => 0])
57  ->setVisibility(\Magento\Catalog\Model\Product\Visibility::VISIBILITY_BOTH)
58  ->setStatus(\Magento\Catalog\Model\Product\Attribute\Source\Status::STATUS_ENABLED)
59  ->save();
60 $categoryLinkManagement->assignProductToCategories($product->getSku(), [5]);
defined('TESTS_BP')||define('TESTS_BP' __DIR__
Definition: _bootstrap.php:60