m2 購(gòu)物車數(shù)量太多,運(yùn)行緩慢或者報(bào)錯(cuò)勤晚,我們可以直接通過命令行的方式直接將客戶的購(gòu)物車生成訂單
- 首先創(chuàng)建命令行,在此不多言
- 創(chuàng)建代碼如下
/**
* @param $customerId 用戶ID
* @param $quoteId 購(gòu)物車ID
* @param $orderId 隨意拿一個(gè)客戶的歷史訂單ID,獲取訂單里面的運(yùn)輸方式和地址
*/
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 '開始創(chuàng)建';
$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;
}