在非对象 /app/code/core/Mage/Core/Block/Template.php(241) 上调用成员函



我知道通常"调用成员函数"错误是因为对象的类没有扩展适当的父类。但是,我的NS_Module_Block_File课已经扩展了Mage_Catalog_Block_Product_View。我在 file.phtml 中的代码:

$object = Mage::getSingleton('catalog/product');
$_product = $object->loadByAttribute('sku','P01');
$id = $_product->getId();

我也把它放在我主题的本地.xml:

<ns_module_file_index>
    <reference name="root">
        <action method="setTemplate"><template>page/1column.phtml</template></action>
    </reference>
    <reference name="content">
        <block type="ns_module/file" name="module.file" template="file.phtml" />
    </reference>
</ns_module_file_index>

我不确定问题出在哪里。请帮忙。提前谢谢你。

如果你看一下 loadByAttribute 的方法:

public function loadByAttribute($attribute, $value, $additionalAttributes = '*')
{
    $collection = $this->getResourceCollection()
        ->addAttributeToSelect($additionalAttributes)
        ->addAttributeToFilter($attribute, $value)
        ->setPage(1,1);
    foreach ($collection as $object) {
        return $object;
    }
    return false;
}

如果 SKU 为"P01"的产品不存在,则不会返回该对象,因为集合为空;将返回 false。

试试这个:

$_product = Mage::getModel('catalog/product')->loadByAttribute('sku','P01');

最新更新