6

In sales_order table product name field is not there but i have to fetch that too. How to fetch the product name ordered by a customer using customer ID?

2
  • get customer ordered order and also order items Right? Commented Dec 11, 2019 at 5:50
  • Grammatically speaking, the title shouldn't have a question mark at the end.
    – ahorn
    Commented Dec 11, 2019 at 14:26

2 Answers 2

4

You can try below:

$order = $this->_objectManager->create('Magento\Sales\Model\Order')->load($orderId);
$orderItems = $order->getAllItems();

If you need more details from order you can review below post.

http://www.codextblog.com/code-snippet/get-order-information-from-order-id-in-magento-2/

4
  • $order->getAllItems(): it will return an array right?......with all column name as index of array..... Commented Dec 11, 2019 at 6:44
  • can i use getData() function inplace of getAllItems()? will that mean the same? Commented Dec 11, 2019 at 6:44
  • You cant use getData here, You can use var_dump to see what data are in object and you can use those.
    – anonymous
    Commented Dec 11, 2019 at 6:47
  • can you please tell me what does getData function do? and what does it return? Commented Dec 11, 2019 at 6:49
3
protected $orderRepository;

public function __construct(
    ...
    \Magento\Sales\Api\OrderRepositoryInterface $orderRepository,
    ....
) {
    ....
    $this->orderRepository = $orderRepository;
    ....
}

//and use in required method as:

$order = $this->orderRepository->get($orderId);
foreach ($order->getAllItems() as $item) {
       echo $item->getName()); // to print all ordered products name
}
2
  • $this->orderRepository->get($orderId): what does this return ? Commented Dec 11, 2019 at 7:01
  • it returns a collection and inside that lot of function ; you can try print_r(get_class_methods($order)); die; to view that and getAllItems() provides all items purchased with that order_id entered Commented Dec 11, 2019 at 9:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.