Magento 2 : Get total spent by customer
Pregunta
Is their any way we can get total amount that has been spend by customer in magento 2 ?
Solución
You can load the order collection for example by customer email, then loop through the orders totalling the value:
use Magento\Sales\Model\ResourceModel\Order\CollectionFactory;
public function __construct(
CollectionFactory $orderCollectionFactory
) {
$this->orderCollectionFactory = $orderCollectionFactory;
}
public function test()
{
$customerEmail="testcustomer@mycoolshop.com";
$total=0;
$orders = $this->orderCollectionFactory->create()
->addAttributeToFilter('customer_email', $customerEmail);
foreach ($orders as $order) {
echo "Order# {$order->getIncrementId()} - Creation Date: {$order->getCreatedAt()} - Value: {$order->getGrandTotal()}". PHP_EOL;
$total=$total+$order->getGrandTotal();
}
echo "Total for customer:".$total.PHP_EOL;
}
Otros consejos
Please add below code in any root file. Please create custom.php file in root of magento folder and check your output.
<?php
ini_set('display_errors', 1);
use Magento\Framework\App\Bootstrap;
require __DIR__ . '/app/bootstrap.php';
$bootstrap = Bootstrap::create(BP, $_SERVER);
$objectManager = $bootstrap->getObjectManager();
$storeManager = $objectManager->get('\Magento\Store\Model\StoreManagerInterface');
$state = $objectManager->get('Magento\Framework\App\State');
$state->setAreaCode('frontend');
$OrderFactory = $objectManager->create('Magento\Sales\Model\ResourceModel\Order\CollectionFactory');
$orderCollection = $OrderFactory->create()->addFieldToSelect(array('*'));
$orderCollection->addAttributeToFilter('customer_email', 'test@zealousweb.com');
$total = 0;
foreach($orderCollection as $orderData)
{
$total = $total + $orderData->getGrandTotal();
}
echo $total;
die();
Licenciado bajo: CC-BY-SA con atribución
No afiliado a magento.stackexchange