2009-05-22 10 views
10

Magento에 간단한 제품으로 업로드되는 많은 종류의 재고 항목이있는 클라이언트 데이터베이스가 있습니다.Magento API : 구성 가능한 제품에 기존의 간단한 제품 할당

이제 그룹화하고 크기 및 색상을 구성 가능한 속성으로 구성 가능한 제품에 할당해야합니다.

Magento API에는 유망한 검색 방법 인 Product_Link 클래스가 있습니다. catalog-product-link.assign (link),하지만 내 인생에서 내가 어떻게 작동하게 만드는지 알아내는 것은 불가능합니다. assignable 제품을 사용하는 방법입니다.

+14

Magento 문서는 쓰레기가 아닙니다. – Dan

+0

오, 거기에 소식이 있습니다! 나는 그 때마다 스팸 메일을 받고 실제로 사용자 문서를 구입합니다. Pfft! – keith

+0

그래, 나는 트위터를 통해 '제안'을 받았다. 실제로, 나는 공식 사용자 가이드를 이미 구입했다. 이것은 개발자에게는 쓸모가 없다. 또한 좋은 독서이지만 10 배 더 두꺼워 야하는 PHP 건축가의 책을 샀다. –

답변

5

글쎄이 메모는 여기에 달려있어 도움이되었습니다. 그래서 저는 기존의 Configurable Product에 간단한 제품을 추가하는 코드를 여러분과 공유 할 생각이었습니다.

이 코드는 단순한 제품이 유효한 추가 제품이라고 가정하고 그렇지 않은 경우 어떻게 될지 잘 모르겠습니다.

private function _attachProductToConfigurable($_childProduct, $_configurableProduct) { 
    $loader = Mage::getResourceModel('catalog/product_type_configurable')->load($_configurableProduct); 

    $ids = $_configurableProduct->getTypeInstance()->getUsedProductIds(); 
    $newids = array(); 
    foreach ($ids as $id) { 
     $newids[$id] = 1; 
    } 

    $newids[$_childProduct->getId()] = 1; 

    $loader->saveProducts($_configurableProduct->getId(), array_keys($newids));     
} 
+0

명령 줄 스크립트에서이 작업을 수행하려고하는데 여기서 실패합니다. $ loader = Mage :: getResourceModel ('catalog/product_type_configurable') -> load ($ _configurableProduct); (첫 번째 줄) 아이디어가 있으십니까? 현재 조사 중이며 결과가있을 경우 알려 드릴 것입니다. –

+0

최근의 자홍수에서 다시 작업하도록 Scimon에서 코드를 업데이트했습니다 : [아래 참조] (http://stackoverflow.com/a/14461333/219467) – aeno

1

필자는 이것은 교육 수준이 아닌 추측이지만 기존 API로는 요구할 수없는 사항이라고 생각합니다. 직접 작성하거나 DB에 직접 접속해야합니다.

+1

EAV db 스키마를 사용하면 DB에 직접 액세스 할 때 '그냥'이 없습니다. 고통!!! –

2

지금 당장이 작업을하고 있습니다.

지금까지 내가 도움이 참조로 이러한 항목을 발견했습니다

내가 잘하면 지금까지 내 코드를 게시하고 있습니다

그것을 업데이트 일단 작동하면 ..

// Set 'item_size' as the super attribute # choose your own attribute! 
// this is the 'choose-able' field that differenciates products 
$super_attributes=array(Mage::getModel('eav/entity_attribute') 
    ->loadByCode('catalog_product','item_size') 
    ->getData('attribute_id') 
); 
$product_collection=Mage::getModel('catalog/product')->getCollection(); 

// Fetch configurable orders 
$product_collection->addFieldToFilter('type_id',Array('eq'=>"configurable")); 
#$product_collection->addFieldToFilter('sku',Array('eq'=>"ASMCL000002")); 

$product_collection->addAttributeToSelect('*'); 

$count=0; 
foreach($product_collection as $product) { 
    $sku = $product->getSku(); 
    echo "SKU: $sku\n"; 

    $simple_children_collection = Mage::getModel('catalog/product')->getCollection(); 
    $simple_children_collection->addAttributeToSelect('*'); 
    $simple_children_collection->addFieldToFilter('sku',Array('like'=>$sku . "-%")); 
    echo "children: "; 
    foreach($simple_children_collection as $child) { 
     $child_sku = $child->getSku(); 
     echo "$child_sku "; 
     #visiblity should be 'nowhere' 
    } 
    echo "\n"; 

if (!$product->getTypeInstance()->getUsedProductAttributeIds()) { 
    # This is a new product without the Configurable Attribue Ids set 
    $product->getTypeInstance() 
    ->setUsedProductAttributeIds($super_attributes); 

    //$product->setConfigurableAttributesData(array($_attributeData)); 
    $product->setCanSaveConfigurableAttributes(true); # Not sure if this is needed. 

    $product->setConfigurableProductsData(''); # Use this to add child products. 

} 


    $count++; 

    try { 
     $product->save(); 
     $productId = $product->getId(); 
     echo $product->getId() . ", $sku updated\n"; 
    } 
    catch (Exception $e){ 
     echo "$sku not added\n"; 
     echo "exception:$e"; 
    } 

} 
echo "\nCount is $count\n"; 

좋아, '간단한'제품을 구별하는 속성으로 'item_size'를 사용합니다. 또한 "구성 가능한"상위 SKU가 하위 SKU의 루트라고 가정합니다. 예를 들어 ABC001은 부모이고 ABC001-SMALL 및 ABC001-LARGE는 단순한 자식입니다.

누군가를 돕는 희망.

+0

당신이 아직이 일을하고 있는지 나는 모르지만 나는 그것을 깨뜨 렸습니다. – Scimon

1

여기 내가 PHP에서 똑같이 해킹하는 방식입니다. 세 가지 관련 표가 있습니다. 내 속성으로 색상과 크기를 사용하고있었습니다. 부모 제품 (구성 가능)이 내 카탈로그에 실제로 존재하지 않습니다. 본질적으로 모델 수준이며 제품은 SKU 수준입니다. LIKE 'parentproductsku %'가 어린이에게 적합합니다. 모든 간단한 제품을 동일한 가격을 공유하는 경우

$query1 = "SELECT * FROM mage_catalog_product_entity WHERE type_id= 'configurable'"; 
    //Find the parent id 
    $statusMessage = "Ok, found a product with a confgurable attribute"; 
    $result1 = $this->runQuery($query1, "query1", $statusMessage); 
    while ($row1 = mysql_fetch_assoc($result1)) { //entering the first loop where products are configurable 
     $this->parentId = $row1['entity_id']; 
     $this->parentSku = $row1['sku']; 

     echo "The SKU was $this->parentSku" . "<br />"; 

    //insert these into the link table for association 
    $query2 = "SELECT * FROM mage_catalog_product_entity WHERE type_id= 'simple' AND sku LIKE '" . $this->parentSku . "%';"; 
    // find the child ids that belong to the parent 
    $statusMessage = "Found some children for $this->parentSku"; 
    $result2 = $this->runQuery($query2, "query2", $statusMessage); 
    while ($row2 = mysql_fetch_assoc($result2)) {//entering the second loop where SKU is like model sku 
     $this->childId = $row2['entity_id']; 
     $this->childSku = $row2['sku']; 

     echo "Now we're working with a child SKU $this->childSku" . "<br />"; 

     //"REPLACE INTO catalog_product_super_attribute SET product_id='".$product->entity_id."', attribute_id='".$attribute->attribute_id."', position='".$position."'"; 
     $query3 = "REPLACE INTO mage_catalog_product_super_attribute (product_id, attribute_id, position) VALUES ('" . $this->childId . "', '76', '0');"; 
     $message3 = "Inserted attribute for color for ID $this->childId SKU $this->childSku"; 
     $result3 = $this->runQuery($query3, "query3", $message3); 

     $query4 = "REPLACE INTO mage_catalog_product_super_attribute_label (product_super_attribute_id, store_id, use_default, value) VALUES (LAST_REPLACE_ID(), '0', '0', 'Color');"; 
     $message4 = "Inserted attribute for Color SKU $this->childSku ID was $this->db->insert_id"; 
     $result4 = $this->runQuery($query4, "query4", $message4); 

     $query5 = "REPLACE INTO mage_catalog_product_super_attribute (product_id, attribute_id, position) VALUES ('" . $this->childId . "', '529', '0');"; 
     $message5 = "Inserted attribute for Product Size SKU $this->childSku"; 
     $result5= $this->runQuery($query5, "query5", $message5); 


     $query6 = "REPLACE INTO mage_catalog_product_super_attribute_label (product_super_attribute_id, store_id, use_default, value) VALUES (LAST_REPLACE_ID(), '0', '0', 'Size');"; 
     $message6 = "Inserted attribute for Size SKU $this->childSku ID was $this->db->insert_id"; 
     $result6 = $this->runQuery($query6, "query6", $message6); 

     $query7 = "REPLACE INTO mage_catalog_product_super_link (product_id, parent_id) VALUES ('" . $this->childId . "', '" . $this->parentId . "');"; 
     $message7 = "Inserted $this->childId and $this->parentId into the link table"; 
     $result7 = $this->runQuery($query7, "query7", $message7); 

     $query8 = "REPLACE INTO mage_catalog_product_relation (parent_id, child_id) VALUES ('" . $this->parentId . "', '" . $this->childId . "');"; 
     $message8 = "Inserted $this->childId and $this->parentId into the link table"; 
     $result8 = $this->runQuery($query8, "query8", $message8); 

     } //end while row 2 the child ID 

      } //end while row 1 the parent id 
1

놀랍게도,이 작품 :

 $childProducts = $configurable->getTypeInstance(true)->getUsedProductIds($configurable); 

     // Don't add this product if it's already there 
     if(!in_array($child->getId(), $childProducts)) {  
      $childProducts[] = $child->getId(); 
     } 


     $existingIds = $configurable->getTypeInstance(true)->getUsedProductAttributeIds($configurable); 
     $newAttributes = array(); 

     foreach($configurable->getTypeInstance(true)->getSetAttributes($configurable) as $attribute) { 

     if(!in_array($attribute->getId(), $existingIds) && $configurable->getTypeInstance(true)->canUseAttribute($attribute) 
      && $child->getAttributeText($attribute->getAttributeCode())) { 

      // Init configurable attribute 
      $configurableAtt = Mage::getModel('catalog/product_type_configurable_attribute') 
       ->setProductAttribute($attribute); 

      // Add new attribute to array 
      $newAttributes[] = array(
       'id'    => $configurableAtt->getId(), 
       'label'   => $configurableAtt->getLabel(), 
       'position'  => $attribute->getPosition(), 
       'values'   => $configurableAtt->getPrices() ? $configurable->getPrices() : array(), 
       'attribute_id' => $attribute->getId(), 
       'attribute_code' => $attribute->getAttributeCode(), 
       'frontend_label' => $attribute->getFrontend()->getLabel(), 
      ); 
     } 
    } 

    if(!empty($newAttributes)) { 

     $configurable->setCanSaveConfigurableAttributes(true); 
     $configurable->setConfigurableAttributesData($newAttributes); 
    } 
     $configurable->setConfigurableProductsData(array_flip($childProducts)); 
     $configurable->save(); 
3

Scimon에 의해 허용 대답에서 코드는 젠토의 최신 버전 (적어도에서에서 더 이상 작동하지 않습니다 1.7). 다행히도 다시 작동하려면 작은 수정이 필요합니다.

private function _attachProductToConfigurable($_childProduct, $_configurableProduct) { 
    $loader = Mage::getResourceModel('catalog/product_type_configurable')->load($_configurableProduct, $_configurableProduct->getId()); 

    $ids = $_configurableProduct->getTypeInstance()->getUsedProductIds(); 
    $newids = array(); 
    foreach ($ids as $id) { 
     $newids[$id] = 1; 
    } 

    $newids[$_childProduct->getId()] = 1; 

    //$loader->saveProducts($_configurableProduct->getid(), array_keys($newids));     
    $loader->saveProducts($_configurableProduct, array_keys($newids));     
} 
+0

나는 예외가 있었습니까? 얼마 전 Magento 개발을 1 년 정도 해본 적이 없으므로 이제이 작업을 진행하십시오. – Scimon

+0

이것은 아마도 수락 된 답변 IMHO에 대한 편집 일 것입니다. –

+0

@Joseph : 나는 글을 쓰는 시점에서 그렇게 할만한 명성을 얻지 못했기 때문에 나는 새로운 대답을 게시했다. – aeno

0

@ aeno의 해결책은 나를 위해 작동하지 않으므로 약간 수정했습니다.이 메서드는 Mage::getModel('catalog/product')->load() 메서드를 통해 인스턴스화 된 제품을 사용하여 테스트되었습니다.

private function _attachProductToConfigurable($childProduct, $configurableProduct) 
{ 
    $childIds = $configurableProduct->getTypeInstance()->getUsedProductIds(); 
    $childIds[] = $childProduct->getId(); 
    $childIds = array_unique($childIds); 

    Mage::getResourceModel('catalog/product_type_configurable') 
     ->saveProducts($configurableProduct, $childIds); 
}