SKU - Magento将可配置产品添加到购物车中

时间:2012-07-16 16:24:53

标签: php magento

我正在玩程序化的购物车娱乐。通过id将产品添加到购物车是没有问题的。

 $params = array(
    'product' => 272,
    'super_attribute' => array(
        22 =>30 ,
    ),
    'qty' => 2,
);


$cart = Mage::getSingleton('checkout/cart'); 
$product = new Mage_Catalog_Model_Product();
$product->load(272); 
$cart->addProduct($product, $params);
$cart->save(); 
Mage::getSingleton('checkout/session')->setCartWasUpdated(true);

但如果我只知道产品sku怎么做呢,我的意思是如何获得可配置产品的产品ID和super_attributes。

Mage::getModel('catalog/product')->loadByAttribute('sku','$sku');

似乎只返回该产品(sku)信息而没有返回special_attribute。

有什么想法吗?

欢呼声, /马尔钦

3 个答案:

答案 0 :(得分:3)

我认为,feeela没有回答这个问题。

一般(没有错误处理):

$sku = 'any-sku-number';
$qty = 1;

$product = Mage::getModel('catalog/product')
    ->loadByAttribute('sku', $sku);

$parentIds = Mage::getResourceSingleton('catalog/product_type_configurable')
    ->getParentIdsByChild($product->getId());

$parent = Mage::getModel('catalog/product')->load(current($parentIds));

if ($parent->getTypeId() === Mage_Catalog_Model_Product_Type::TYPE_CONFIGURABLE) {
    $paramsSuperAttribute = array('super_attribute' => array());

    foreach ($parent->getTypeInstance(true)->getConfigurableAttributes($parent) as $attribute) {
        $paramsSuperAttribute['super_attribute'][$attribute->getProductAttribute()->getAttributeId()] =
            (int) $product->getData($attribute->getProductAttribute()->getAttributeCode());
    }
}

$params = array('qty' => $qty);

现在,有两种方法可以通过sku将产品添加到购物车中:

编程:

$cart = Mage::getSingleton('checkout/cart');

$cart->addProduct(isset($parent) ? $parent : $product, array_merge($params, $paramsSuperAttribute))->save();

Mage::getSingleton('checkout/session')->setCartWasUpdated(true);

by url:

$addToCartUrl = Mage::helper('checkout/cart')
    ->getAddUrl(isset($parent) ? $parent : $product, $params);

if (isset($parent)) {
    $addToCartUrl .= '?' . http_build_query($paramsSuperAttribute);
}

// now you can use this url like this (controller action)
$this->getResponse()->setRedirect($addToCartUrl);
return;

答案 1 :(得分:0)

您可以通过获取由SKU过滤的集合来检索产品:

$searchForThisSku = 'p_1234';

/** @var $productCollection Mage_Catalog_Model_Resource_Product_Collection */
$productCollection = Mage::getModel( 'catalog/product' )
    ->getResourceCollection()
    ->addFieldToFilter( 'sku', $searchForThisSku );

/** @var $product Mage_Catalog_Model_Product */
$product = $productCollection->getFirstItem();

// you should have the product now, maybe it isn't even necessary to get the ID
$product->getId();

// all in one line:
$productId = (int) Mage::getModel( 'catalog/product' )
    ->getResourceCollection()
    ->addFieldToFilter( 'sku', $searchForThisSku )
    ->getFirstItem()
    ->getId();

答案 2 :(得分:0)

尝试

/** @product Mage_Catalog_Model_Product */
$product = Mage::getModel('catalog/product');

$sku = 'sku';
$product->load($sku, 'sku');