0

I have an annoying bug in the Bestsellers table on the Dashboard page showing incorrect info about the non-existing products with weird prices and quantity sold.

I found that this row is collected of the products with product_id=0.

So, I need to delete all orders containing product_id=0 and all related data - invoices, shipments, credit memos, anything else related to these orders that may cause issues if not cleaned.

How can this be done in PHP or MySQL, please? I'm running Magento 2.4.3.

Thank you.

1 Answer 1

0

You can get the order collection using this one :

protected $_order;
protected $orderRepository;

 public function __construct(\Magento\Sales\Model\ResourceModel\Order\CollectionFactory $order, \Magento\Sales\Model\OrderRepository $orderRepository)
 {
    $this->_order  = $order;
    $this->orderRepository  = $orderRepository;
 }

 public function execute()
 {
    $orderCollection = $this->_order->create();
    
    $product_id = 0; //YOUR PRODUCT ID

    $orderCollection->getSelect()
            ->join(
                'sales_order_item',
                'main_table.entity_id = sales_order_item.order_id'
            )->where('product_id = '.$product_id);

        $orderCollection->getSelect()->group('main_table.entity_id');

        foreach ($orderCollection as $order) {
             $this->orderRepository->delete($order);
        }
    }
10
  • Thank you for your answer, but I'm not skilled enough to write necessary code for order and related data deletion. I don't even understand where and how to insert your code :-(
    – Frenger
    Oct 14, 2021 at 8:27
  • The code need to write like on any controller action which perform the task of delete the order for you. Oct 14, 2021 at 9:14
  • I just added the delete code as well, now you just need to impertinent into your controller or something. Oct 14, 2021 at 10:08
  • Is it possible just to create and run separate php file with necessary code? Also, does the delete($order) function deletes specific order only, or all data related to it (like invoices, shipments, credit memos)? Thank you.
    – Frenger
    Oct 14, 2021 at 11:30
  • yes you can create seprate like root script or something. Delete only orders. And if above answer help then upvote and accept as solution so it will help other in community. Oct 14, 2021 at 11:42

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.