m2 购物车数量太多,运行缓慢或者报错,我们可以直接通过命令行的方式直接将客户的购物车生成订单
- 首先创建命令行,在此不多言
- 创建代码如下
/**
* @param $customerId 用户ID
* @param $quoteId 购物车ID
* @param $orderId 随意拿一个客户的历史订单ID,获取订单里面的运输方式和地址
*/
public function createNewOrder($customerId, $quoteId, $orderId) {
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$quoteRepository = $objectManager->get(\Magento\Quote\Api\CartRepositoryInterface::class);
$quoteManagement = $objectManager->get(\Magento\Quote\Api\CartManagementInterface::class);
$orderRepository = $objectManager->get(\Magento\Sales\Api\OrderRepositoryInterface::class);
$serializer = $objectManager->get(\Magento\Framework\Serialize\Serializer\Json::class);
$order = $orderRepository->get($orderId);
if (empty($order->getId())) {
echo '订单不存在';
}
$newQuote = $quoteRepository->get($quoteId);
$newQuote->setStoreId(2);
$newQuote->getShippingAddress()->setCollectShippingRates(true)
->collectShippingRates()->setShippingMethod($order->getShippingMethod());
$newQuote->getShippingAddress()->setShippingDescription($order->getShippingDescription());
foreach ($newQuote->getAllVisibleItems() as $item) {
$options = [];
$productOptions = $item->getProduct()->getTypeInstance()->getOrderOptions($item->getProduct());
if ($productOptions) {
$productOptions['info_buyRequest']['options'] = $this->_prepareOptionsForRequest($item);
$options = $productOptions;
}
$addOptions = $item->getOptionByCode('additional_options');
if ($addOptions) {
$options['additional_options'] = $serializer->unserialize($addOptions->getValue());
}
$item->setProductOrderOptions($options);
$item->save();
print_r($options);
}
$quoteRepository->save($newQuote);
echo '开始创建';
$newOrder = $quoteManagement->submit($newQuote);
echo '成功,orderID:' . $newOrder->getId();
}
protected function _prepareOptionsForRequest($item)
{
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$newInfoOptions = [];
$optionIds = $item->getOptionByCode('option_ids');
if ($optionIds) {
foreach (explode(',', $optionIds->getValue()) as $optionId) {
$option = $item->getProduct()->getOptionById($optionId);
$optionValue = $item->getOptionByCode('option_' . $optionId)->getValue();
$group = $objectManager->get(
\Magento\Catalog\Model\Product\Option::class
)->groupFactory(
$option->getType()
)->setOption(
$option
)->setQuoteItem(
$item
);
$newInfoOptions[$optionId] = $group->prepareOptionValueForRequest($optionValue);
}
}
return $newInfoOptions;
}