电子商务由几个丰富的元素组成,Magento已成功覆盖了所有这些元素,也许这就是为什么它成为世界500强的的选择。但通常情况下,每个Magento项目都会通过定制来为商城提供个性化的功能效果。

从事magento定制开发工作,我们遇到了太多的不同的定制要求,有时我们听到客户的一些需求感到震惊,每个企业都有自己的故事,自己的需求和个性化需求,这就是它独特的原因。

最近,其中一位客户告诉我们,他花了大量时间来确定订单中有多少产品数量。他想节省时间,以便将宝贵的时间投入到其他业务中。也许你也需要知道订单产品总数量,所以这段代码可以帮助你节省时间。因此,我们已经确定了使用以下两种方法快速完成其工作的两种方法。

方法1:标准Magento方法

public function __construct(\Magento\Sales\Model\OrderFactory $orderFactory)
{
    $this->orderFactory = $orderFactory;
}
 
public function execute()
{
     $orderId = 5;  //PASS YOUR ORDER ID HERE
     $order = $this->orderFactory->create()->load($orderId);
     $orderItems = $order->getAllItems();
     $total_qty = 0;
     foreach ($orderItems as $item)
     {
          $total_qty = $total_qty + $item->getQtyOrdered();
     }
     return $total_qty;
}

方法2:使用对象管理器

$order_id = 5;  //PASS YOUR ORDER ID HERE
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$order = $objectManager->create('Magento\Sales\Model\Order')->load($order_id);
$orderItems = $order->getAllItems();
$total_qty = 0;
foreach ($orderItems as $item)
{
   $total_qty = $total_qty + $item->getQtyOrdered();
}
 
echo $total_qty;