在 Magento 2 中导入报价并将产品添加到购物车

Import quote and Add product to cart in Magento 2

正在创建外部脚本以导入 Quotes/Cart(其他 CMS)。我的代码能够添​​加报价但不能创建购物车。需要所有引用的项目在用户登录到他们的帐户时显示。我也启用了持久购物车。

   class QuoteMove extends \Magento\Framework\App\Http implements \Magento\Framework\AppInterface 


  public function __construct(
    \Magento\Framework\ObjectManagerInterface $objectManager,
    \Magento\Framework\Event\Manager $eventManager,
    \Magento\Framework\App\AreaList $areaList,
    \Magento\Framework\App\Request\Http $request,
    \Magento\Framework\App\Response\Http $response,
    \Magento\Framework\ObjectManager\ConfigLoaderInterface $config,
    \Magento\Framework\App\State $state,
    \Magento\Framework\Filesystem $fileSystem,
    \Magento\Framework\Registry $registry,
    \Magento\Store\Model\Store $store,
    \Psr\Log\LoggerInterface $logger,
    \Magento\Framework\File\Csv $csvProcessor,
    \Magento\Quote\Model\QuoteFactory $quote,
    \Magento\Catalog\Model\Product $product
)


                $quotes = []; 
                $email = email@domain.com;
                $qty = xxx ;
                $customerId  = xxx ;

                $this->customer = $this->getCustomerByEmail($email);
                    $customerId = $this->customer->getId();

                    $quote = $this->quotes[$customerId];
                    $quote->setCustomerNote(_NOTES_);
                    $quote->setCouponCode(_COUPON_CODE_);

                    $product = $this->_product->load('PRODUCT_ID');  //PRODUCT_ID= xx
                    $params = [];
                    $params['product'] = $productId;
                    $params['qty'] = intval($qty);
                    $options = [];
                    $options[_ATTRIBUTE_] = _VALUE_]   ;
                    $params['super_attribute'] = $options;

                    $config = new \Magento\Framework\DataObject();
                    $config->setItem($params);
                    $quote->addProduct($product,$config);
                    $quote->save();      

                How to Save items in cart now ??

所以当用户登录帐户时可以查看购物车中的商品。

这就是您需要将产品添加到购物车的方式。

public function __construct(
 \Magento\Catalog\Model\ProductRepository $productRepository, 
\Magento\Checkout\Model\Cart $cart, 
\Magento\Framework\Data\Form\FormKey $formKey){
            $this->_productRepository = $productRepository;
            $this->_cart = $cart;
            $this->formKey = $formKey;
        }



$params = array(
                'product' => --productID--,
                'qty' => $product->getQty()
            );
    $_product = $this->_productRepository->getById(--productID--);
        $this->_cart->addProduct($_product,$params);
                    $this->_cart->save();

将产品添加到购物车后,您可以将其保存到报价中。

这是答案,我已经开始工作了:

更改 $quote->save();到 $quote->collectTotals()->save();

之后加载报价 ID 并将 updated_at 字段日期更新为与创建日期相同。现在登录并检查您的购物车。项目将在那里被查看。