Magento,自定义集合的附加项目

时间:2012-11-30 12:02:04

标签: magento magento-1.7

我正在尝试将一些项添加到自定义创建的集合中。阅读Alan Storm varien data collectionSO question我得到了几个不同的选择。

以下是使用Varien_Data_Collection的一个选项:

    $myResultCollection = new Varien_Data_Collection();
    $mybanner = new Varien_Object();
    foreach($myBannersCollection as $banner){
        $mybanner = $banner;
        $search_text = explode(",", $banner->getsearch_text());
        foreach ($search_text as $txt){
            if (stripos($currentProdName,$txt) !== false) {
                $myResultCollection->addItem($mybanner);
            }
        }
    }

此代码抛出以下错误:

Item (Dts_Banners_Model_Bannersadmin) with the same id "10" already exist

以下是代码的另一种变体,使用我目前使用的模型中的自定义集合:

    $myResultCollection = Mage::getModel('banners/bannersadmin');
    foreach($myBannersCollection as $banner){
        $search_text = explode(",", $banner->getsearch_text());
        foreach ($search_text as $txt){
            if (stripos($currentProdName,$txt) !== false) {
                $myResultCollection->addItem($banner);
            }
        }
    }

但是这个显示以下错误(没有显示所有内容,是很长的方式):

Invalid method Dts_Banners_Model_Bannersadmin::addItem(Array
(
    [0] => Dts_Banners_Model_Bannersadmin Object
        (
            [_eventPrefix:protected] => core_abstract
            [_eventObject:protected] => object
            [_resourceName:protected] => banners/bannersadmin
            [_resource:protected] => 
            [_resourceCollectionName:protected] => banners/bannersadmin_collection
            [_cacheTag:protected] => 
            [_dataSaveAllowed:protected] => 1
            [_isObjectNew:protected] => 
            .......

我做错了什么?

2 个答案:

答案 0 :(得分:2)

问题#1:要添加到Varien_Data_Collection实例的项目需要在集合的上下文中包含不同的ID。

问题#2: Dts_Banners_Model_Bannersadmin不是Varien_Data_Collection的实例。

答案 1 :(得分:0)

发现错误。在for..each内部,我试图多次添加相同的对象,并且当ID重复时,错误是正确的。正确的代码如下:

$myResultCollection = new Varien_Data_Collection();
$mybanner = new Varien_Object();
$found = false;
foreach($myBannersCollection as $banner){
    $mybanner = $banner;
    $search_text = explode(",", $banner->getsearch_text());
    foreach ($search_text as $txt){
        if (stripos($currentProdName,$txt) !== false) {
            $mybanner = $banner;
            $myResultCollection->addItem($mybanner);
            $found = true;
        }
        if ($found) break;
    }
}

编辑 @benmarks你对我的第一个片段的回答是正确的,正如我在asnwer上所评论的那样。但在第二个我不太确定。在Magento中,并非所有集合都“从基本的Varien_Data_Collection”继承“