1

I found out I have some quote objects* that have some invalid data or item data that cause a huge lag every time a customer tries to add items to cart or view cart.

*quote object: database records from quote,quote_item,quote_address...

This is what I've got so far:

/**
 * @param string $email
 * @return bool
 */
function deleteCustomerQuote($email) {
    // \vendor\magento\module-customer\etc\di.xml : \Magento\Customer\Api\CustomerRepositoryInterface = \Magento\Customer\Model\ResourceModel\CustomerRepository
    // \vendor\magento\module-quote\etc\di.xml : \Magento\Quote\Api\CartRepositoryInterface = \Magento\Quote\Model\QuoteRepository
    /** @var \Magento\Framework\App\ObjectManager $objectManager */
    $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
    /** @var \Magento\Customer\Api\CustomerRepositoryInterface $customerRepository */
    $customerRepository = $objectManager->get('\Magento\Customer\Api\CustomerRepositoryInterface');
    /** @var \Magento\Quote\Api\CartRepositoryInterface $cartRepository */
    $cartRepository = $objectManager->get('\Magento\Quote\Api\CartRepositoryInterface');
    try {
        $customer = $customerRepository->get($email);
        $cart = $cartRepository->getForCustomer($customer->getId()); // Magento\Quote\Api\Data\CartInterface
        $cartRepository->delete($cart);
        return true;
    } catch (\Exception $exception) {
        return false;
    }
}

and also this:

/**
 * @param string $email
 * @return bool
 */
function deleteAllCustomerQuotes($email) {
    $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
    /** @var \Magento\Customer\Api\CustomerRepositoryInterface $customerRepository */
    $customerRepository = $objectManager->get('\Magento\Customer\Api\CustomerRepositoryInterface');
    /** @var \Magento\Quote\Model\ResourceModel\Quote\CollectionFactory $quoteCollectionFactory */
    $quoteCollectionFactory = $objectManager->get('\Magento\Quote\Model\ResourceModel\Quote\CollectionFactory');
    /** @var \Magento\Quote\Api\CartRepositoryInterface $cartRepository */
    $cartRepository = $objectManager->get('\Magento\Quote\Api\CartRepositoryInterface');
    try {
        $customer = $customerRepository->get($email);
        $customerId = $customer->getId();
        $quoteCollection = $quoteCollectionFactory->create()->addFieldToFilter('customer_id', $customerId);
        if ( $quoteCollection->getSize() ) {
            /** @var \Magento\Quote\Model\Quote $item */
            foreach ( $quoteCollection as $item ) {
                $cartRepository->delete($item);
            }
        }
        return true;
    } catch (\Exception $exception) {
        return false;
    }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.