Magento2: existing quote doesn't load through a cron job
题
I want to get an existing quote through a cron job, but it returns null.
Want get through this $this->quoteFactory->create()->loadByCustomer($custoemrId)
or
$this->quoteFactory->create()->load($quoteId)
.
It works without cron job but I need through a cron job.
$checkCartExist = $this->quoteFactory->create()->loadByCustomer($customerId);
$checkCartExist->getAllVisibleItems();
var_dump($checkCartExist->getData()); // returns 0 through a cron
if (!$checkCartExist['entity_id']) {
$cartId = $this->cartManagementInterface->createEmptyCart(); //Create empty cart
$quote = $this->cartRepositoryInterface->get($cartId); // load empty cart quote
} else {
$quote = $this->cartRepositoryInterface->getForCustomer($customerId);
}
Cron works because each time it created a new quote item.
解决方案
You can give a try with below code in your cron file for getting quote items with customer id.
protected $quoteFactory;
public function __construct(
\Magento\Quote\Model\QuoteFactory $quoteFactory
) {
$this->quoteFactory = $quoteFactory;
$this->quoteModel=$quoteModel;
}
public function getQuoteCollection($customerId)
{
$quote = $this->quoteFactory->create()->getCollection()->addFieldToFilter('customer_id',$customerId);
return $quote;
}
Hope it helps!!!
其他提示
Instead using Quote factory, use quote RepositoryrepMagento\Quote\Api\CartRepositoryInterface::getForCustomer
This method needs two param $customerId, array $sharedStoreIds = []
So you have to provide those two parameters
/** * Where $this->quote is instance of Magento\Quote\Api\CartRepositoryInterface */ $this->quote->getForCustomer({CustomerId}, [{MyStoreId}]);