Hello,
I need the creation date of an order from the past in which the the current user (who is logged in) has bought the current product (whose product detail page is opened currently). What would my query look like?
Here an example that should be useful. Although I have to guess that you search for the latest order date as a customer could have more than one order for that product.
The query has to be executed within the ProductPageLoadedEvent
$criteria = new Criteria();
// filter the criteria for orderlineitems by customer id and product id
$criteria->addFilter(new EqualsFilter('order.orderCustomer.customerId', $customer->getId()));
$criteria->addFilter(new EqualsFilter('productId', $page->getProduct()->getId()));
// add an aggregation to get the max (latest) date the product was included within an order of the customer
$criteria->addAggregation(new MaxAggregation(
'latest-order',
'order.orderDateTime'
));
$search = $this->orderLineItemRepository->search($criteria, $event->getContext());
// If needed this will include all orderlineitems the customer is related to
$lineItems = $search->getEntities();
// This will get the result of the aggregation
/** @var MaxResult $aggregation */
$latestOrder = $search->getAggregations()->get('latest-order');
// If the customer bought the product, here you have the date of the latest order.
$latestOrderDate = $latestOrder->getMax();
You may tweak that further to filter by paid orders etc.
This is giving NULL on all customers, even ones who have bought this product in the past.
Using var_dump(), I found out that it is unable to return any order in $search.
I tried changing the customer id to:
order.orderCustomer.customerId’
But its still not resolved.
Your change is correct. I will update my answer together with one more change (the context shouldn’t be SalesChannel in that case).
However, the query works otherwise.
Do you use the order_line_item.repository?
Do you have products with variations?
And to debug you may remove the product and/or the customer filter to check if it returns something then.
Okay so in my case, the issue was that the customer id i was getting from context was different from the one in database. I deleted all my customers and then created new ones and the code worked just fine. Thank you so much for all the help.