![](/img/trans.png)
[英]magento:Fatal error: Call to undefined method Varien_Data_Collection::addFieldToFilter()
[英]Magento : Get data from Varien_Data_Collection
大家好! 我希望你能給我一個線索,因為我還是Magento的老板。
我嘗試顯示我在數組中獲得的產品列表。 在Mage/Catalog/Block/Product/List.php
,我創建了一個新的Varien_Data_Collection()
,其中我推送了我的產品對象(使用->addItem($product)
)。
然后我返回我的自定義集合, List.php
類使用它來顯示產品列表。
當我在瀏覽器中調用頁面時,我有正確數量的顯示產品,當我點擊它以查看產品頁面時,我得到了正確的頁面。
但是,所有數據(如產品名稱,價格等)都是空的。 我想List類用來捕獲這些數據的方法失敗了我的Varien_Data_Collection
對象。
為了說明,這是我的代碼示例:
// getting a particular product
$mainProduct = Mage::getModel('catalog/category')->load($currentCat->getId());
$mainProduct = $mainProduct->getProductCollection();
$mainProduct = $mainProduct->addAttributeToFilter('product_id', $_GET['cat_id']);
// creating a custom collection
$myCollection = new Varien_Data_Collection();
foreach ($mainProduct as $product) {
// getting my particular product's related products in an array
$related = $product->getRelatedProductIds();
if ($this->array_contains($related, $_GET['cat_id'])) {
// if it suits me, add it in my custom collection
$myCollection->addItem($product);
}
}
return $myCollection;
這就是我在列表頁面中得到的內容:
當我var_dump($myCollection)
,我可以看到沒有引用['name']
, ['price']
等字段。 只有['product_id']
和我不關心的許多其他領域。
我的最終問題是:如何將包含這些產品數據的集合返回給我的List類? 我知道它的解釋很差,但我的英語非常有限,我盡力做到最好:(
對類別調用->getProductCollection()
僅返回已創建集合中每個產品的框架數據。 如果你想要每個產品的完整數據,你需要加載它們,所以在你的foreach
循環中你將擁有:
$product = Mage::getModel('catalog/product')->load($product->getId());
但是,構建集合的方式並不是最好的工作方法 - 您永遠不必創建自己的Varien_Data_Collection
對象,而應該創建一個產品集合,如下所示:
$collection = Mage::getModel('catalog/product')->getCollection();
然后在加載collecion( foreach
循環或對集合調用->load()
將作為2個示例)之前,您可以根據您的要求過濾集合。 您可以使用本機Magento方法執行此操作,其中一個方法已經在使用( addAttributeToFilter()
),或者我更喜歡從集合中提取select對象並以這種方式應用過濾:
$select = $collection->getSelect();
然后,您可以針對此select對象運行所有Zend_Db_Select
類方法以過濾集合。
http://framework.zend.com/manual/1.12/en/zend.db.select.html
加載集合后,其中的產品將包含完整的產品數據。
首先pelase不使用$ _GET變量,使用Mage::app()->getRequest()->getParams();
為什么不嘗試從一開始就正確地構建您的集合?
這是你的代碼所做的:
$mainProduct = Mage::getModel('catalog/category')->load($currentCat->getId());
$mainProduct = $mainProduct->getProductCollection();
$mainProduct = $mainProduct->addAttributeToFilter('product_id', $_GET['cat_id']);
得到一個產品,我的意思是你加載一個類別然后加載產品集合,然后按產品ID過濾..為什么不:
$mainProduct = Mage::getModel('catalog/product')->load($yourSearchedId);
我也不明白為什么你用$ _GET ['cat_id']過濾產品,看起來像是一個類別ID ...
總而言之,如果您准確解釋您想要找到的內容,您可以獲得更多幫助。 看起來您正在嘗試查找具有相關產品的所有產品。 那么為什么不正確地為該給定產品設置相關產品並獲得相關產品集合。
$_product->getRelatedProductCollection();
更新:
既然你已經清除了你的請求,試試這個:
$relatedIds = $product->getRelatedProductIds();
$myCollection = Mage::getModel('catalog/category')
->load($currentCat->getId())
->getProductCollection();
$myCollection->addAttributeToFilter('product_id', array("in",$relatedIds));
//也addAttributeToSelect你可能需要的所有屬性,如名稱等$ $ myCollection-> load(); //也許你不需要在這里加載
請記住,我沒有測試這個代碼,它是從我的頭頂寫的,測試它。 但我希望你有這個主意。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.