Get the date of last purchase of product, by customer

by Bawsi   Last Updated September 24, 2018 10:09 AM

How can I get the last date that a customer has purchased a product?

Thank you



Answers 1


First, filter a Order Collection by customer_id sorted by created_at DESC

For example like

$ordercollection =$this->orderCollectionFactory->create()->addFieldToSelect(array('*'));
$ordercollection->setOrder('created_at','DESC');

where $this->orderCollectionFactory is of type

\Magento\Sales\Model\ResourceModel\Order\CollectionFactory

and I assume an object has been injected and assigned to $this->orderCollectionFactory via a constructor

This makes sure you have the most recent orders available in first.

Then, loop through them like

foreach ($ordercollection1->getItems() as $order) {

    $items = $order->getAllItems();
    foreach($items as $item) {
        if($item->getSku() == 'your_Sku')
        {
            //YOU HAVE FOUND YOUR PRODUCT
            //DO SOMETHING, like when the order was originally created and STOP THE LOOPING by returning
            return $order->getCreatedAt();
        }
    }

You could continue looping and you may encounter you product in another order later on, but this would be an older order, hence my decision to return.

Perhaps this is not the most accurate solution to what you need, but I hope you already have a good idea how to continue.

Marjan
Marjan
September 24, 2018 09:58 AM

Related Questions



Magento 2 Add Extra Field(Attribute) at Tire Price

Updated December 30, 2017 06:09 AM



After add product to cart page goes to top issue

Updated July 25, 2017 10:09 AM