Magento 对非对象/app/code/core/Mage/core/Block/Template.php(241)调用成员函数getId()

Magento 对非对象/app/code/core/Mage/core/Block/Template.php(241)调用成员函数getId(),magento,Magento,我知道通常“调用成员函数”的错误是因为对象的类没有扩展适当的父类。但是,我的NS_模块块文件类已经扩展了Mage_目录块产品视图。file.phtml中的我的代码: $object = Mage::getSingleton('catalog/product'); $_product = $object->loadByAttribute('sku','P01'); $id = $_product->getId(); 我还将其放在主题的local.xml中: <ns_module

我知道通常“调用成员函数”的错误是因为对象的类没有扩展适当的父类。但是,我的NS_模块块文件类已经扩展了Mage_目录块产品视图。file.phtml中的我的代码:

$object = Mage::getSingleton('catalog/product');
$_product = $object->loadByAttribute('sku','P01');
$id = $_product->getId();
我还将其放在主题的local.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>

第/1页column.phtml
我不确定问题出在哪里。请帮忙。提前感谢您。

请尝试以下方法:

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

如果查看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。

谢谢。得到了同样的东西。此外,因为这是对数千个SKU的迭代,所以我不得不使用getSingleton。谢谢。你说得对。似乎是数字SKU导致了错误。