문제

나는 다양한 재고 품목이있는 클라이언트 데이터베이스를 가지고 있는데,이 품목은 간단한 제품으로 Magento에 업로드됩니다.

이제 그룹화하여 크기와 색상이 구성 가능한 속성 인 구성 가능한 제품에 할당해야합니다.

Magento API에는 유망한 방법이있는 Product_Link 클래스가 있습니다. Catalogue-Product-Link.assign (링크), 그러나 나는 내 삶에 대해 구성 가능한 제품으로 작동하도록해야 할 논쟁을 알아낼 수 없으며,이를 제공하면 할당이 어떻게 사용되었는지를 제공합니다.

도움이 되었습니까?

해결책

여기에 노트 가이 실행에 도움이되었습니다. 그래서 기존 구성 가능한 제품에 간단한 제품을 추가하기 위해 코드를 공유 할 것이라고 생각했습니다.

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

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 ) );                
}

다른 팁

Scimon의 수락 된 답변의 코드는 최근 버전의 Magento (적어도 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 ) );                
}

나는 지금이 일을하고있다.

지금까지 나는이 항목들이 참고 문헌으로 도움이된다는 것을 알았습니다.

지금까지 내 코드를 게시하고 일단 작동하면 업데이트하길 바랍니다 ..

// 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는 단순한 어린이입니다.

그것이 누군가를 돕기를 바랍니다.

나는 교육받지 않은 추측이지만, 기존 API로 당신이 요구하는 것은 무엇을 할 수 없다고 생각합니다. 직접 작성하거나 DB에 직접 도착해야합니다.

다음은 PHP 로이 작업을 수행 한 해킹 방식입니다. 세 가지 관련 테이블이 있습니다. 나는 내 속성으로 색상과 크기를 사용하고있었습니다. 내 부모 제품 (구성 가능)은 실제로 카탈로그에 존재하지 않습니다. 그것들은 본질적으로 모델 수준이며 제품은 SKU 수준입니다. 따라서 '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

놀랍게도, 이것은 모든 간단한 제품이 동일한 가격을 공유한다면 작동합니다.

        $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();

@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 );
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top