2016-06-08 75 views
0

我正在編寫一些腳本來自動化網店中的一些內容。通過比較Magento中的自定義屬性加載產品信息

我瀏覽過很多論壇和問題。
現在我幾乎已經完成了我的腳本,但有一件小事情不起作用,但我無法想象我做錯了什麼。

該腳本的目標是獲得與數組中值相同的屬性值的產品(從數據庫中提取)。

因此,這裏是我的代碼:

ini_set('display_errors', 1); 
ini_set('display_startup_errors', 1); 
error_reporting(E_ALL); 
require_once('../app/Mage.php'); 
require_once('db.php'); 


Mage::app(); 

$db = db_connection(); 

$collection = Mage::getModel('catalog/product')->getCollection(); 

$collection->addAttributeToSelect('ean'); 


$getean = $db->prepare('SELECT ean_l FROM mytable'); 
$getean->execute(); 
$allean = $getean->fetchAll(); 


foreach($allean as $ean) { 

    $collection->addFieldToFilter(array(
     array('attribute'=>'ean','eq'=>'' . $ean['ean_l'] . ''),  
    )); 
    echo 'ean_l: ' . $ean['ean_l'] . '<br>'; 

    foreach ($collection as $product) { 

     echo $product['entity_id']; 

    } 


} 

因此,這裏是它如何工作的:

我們選擇一個屬性(EAN)。
我們從數據庫中得到所有可用數字的列表。
我們通過列表循環並將任何產品與ean編號進行比較。
然後我們循環訪問並獲取相應產品的ID。
然而,所有$product['entity_id']都是273. entity_id是273是正確的,但也有產品274具有相應的數字。

這是從劇本的結果(這是很多更多):

result

那麼這是爲什麼?因爲在我的推理中,它在每個循環中都會更改ean_l,並使其與屬性值相等。
然後它應該改變集合,對吧?
那麼它不應該至少在某個時候顯示274?

這個問題不是特別針對Magento程序員,但其他程序員也可以提供幫助,所以我想把它發佈到SO上。

回答

0

Magento具有強大的過濾和查詢集合。如果不滿足,您可以隨時將自定義查詢擴展爲getSelect函數。一些信息here

使用addFieldToFilter進入該foreach將過濾其他值迭代過濾後。所以這不好。

$allean = array("of", "ean", "values", "needed", "for", "filtering"); 

$collection = Mage::getModel('catalog/product')->getCollection(); 
$collection->addAttributeToSelect('ean'); 
//addAttributeToFilter for EAV collections 
$collection->addAttributeToFilter('ean', array('in' => $allean)); //not addFieldToFilter 
$collection->getColumnValues('entity_id'); 

var_dump($collection); //will output an array of product_ids 

選擇,如果你想按ean值則應刪除getColumnValues和運行組命令。 你可以找到更多的信息here

或者您也可以刪除getColumnValues,手動啓動foreach($collection as $product)並手動設置組,或者按照您的要求使用這些過濾的產品。

相關問題