试试这个代码:
use Magento\Checkout\Model\Cart as Quote;
class Add {
protected $quote = null;
public function __construct( Quote $quote){
$this->quote = $quote;
}
public function test(\Magento\Catalog\Model\Product $product){
$options = ['qty'=> 1];
$this->quote->addProduct($product, $options);
//OR $this->quote->addProductsByIds([$product->getId()]);
$this->quote->save();
}
}
或者
public function test(\Magento\Catalog\Model\Product $product){
$quote = $this->_objectManager->get(\Magento\Checkout\Model\Cart:class);
$options = ['qty'=> 1];
$quote->addProduct($product, $options);
//OR $quote->addProductsByIds([$product->getId()]);
$quote->save();
}