Как удалить товар в корзине по артикулу или товару в magento 2


Я извлек все товары из корзины и удалил товар с предложением, сопоставив его с артикулом товара,

Вот мой код.

protected $checkoutSession;
protected $_itemModel;
protected $cart;
public function __construct(
    \Magento\Framework\App\Action\Context $context,
    \Magento\Checkout\Model\Session $checkoutSession,
    \Magento\Checkout\Model\Cart $cart,
    \Magento\Quote\Model\Quote\Item $itemModel
    { 
     $this->cart = $cart;
     $this->checkoutSession = $checkoutSession;
     $this->_itemModel = $itemModel;
     parent::__construct($context);
    }

 public function execute() {
       $quote = $this->checkoutSession->getQuote();
                $quoteItems = $quote->getAllVisibleItems();
                foreach($quoteItems as $item) {
                    $cartquote = $this->cart->getQuote();   

                    $productSku = $item->getProduct()->getSku();
                    //$this->logger->info('ItemproductSku'.$productSku);
                    $checkExistedSKu  = $this->getExistedSKu($productSku);
                    if($checkExistedSKu){
                        $itemId = $item->getItemId();
                        //$this->cart->removeItem($itemId)->save();
                        $this->_itemModel->load($item->getItemId())->delete();
                    }                       

                    $cartquote->updateItem($item->getId(), array( 'qty' => 1));
                    $cartquote->save();
                }

    public function getExistedSKu($productSku){
       $connection = $this->getConnection();
       $sql = "select * from custom_table where sku='".$productSku."'";
       $resultProduct = $connection->query($sql);
       $resultQuery = $resultProduct->fetchAll();

      if(!empty($resultQuery)){ 
        $parent_sku = $resultQuery[0]['parent_sku'];
        return true;
       }
      }else{
       return false;
      }
      }

Я получаю артикул товара по идентификатору элемента и сверяюсь со своей пользовательской таблицей, если артикул товара присутствует в таблице, я удаляю этот элемент предложения и обновляю все остальные элементы по количеству 1.

Этот код не работает для меня, может ли кто-нибудь разобраться, где я здесь ошибаюсь,

Любая помощь будет оценена по достоинству!!

Author: jafar pinjar, 2019-05-20

1 answers

Обновление для вашего комментария

foreach($quoteItems as $item) {

                $productSku = $item->getSku();
                $checkExistedSKu  = $this->getExistedSKu($productSku);
                if($checkExistedSKu){
                    $item->delete();
                    continue;
                }                       

                $item->setQty(1);
                $item->save();
            }
$quote->collectTotals();
 1
Author: the light, 2019-05-20 11:42:56