You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Magento 1中单次调用多次执行getResourceSingleton()失效问题求助

Fixing Magento 1 Category Tree Loading Issue with Multiple getResourceSingleton() Calls

Hey there, let's break down why your code is misbehaving and fix it right away!

The Root Cause

Magento's getResourceSingleton() method returns a single, reusable instance of the resource model throughout your request lifecycle. When you call load() on it the first time, the category tree data gets loaded into that instance. The second time you call Mage::getResourceSingleton('catalog/category_tree')->load(), you're not getting a fresh object—you're just grabbing the same already-loaded instance. Since the tree is already populated, the second load() call does nothing, which breaks your expected functionality.

The Simple Fix

You only need to fetch the singleton instance once, then reuse it for all your tree operations. Here's your corrected code:

// Fetch the singleton instance ONCE and load it
$tree = Mage::getResourceSingleton('catalog/category_tree')->load(); 
$root = $tree->getNodeById($rootCategoryId); 

if ($root && $root->getId() == 1) { 
    $root->setName(Mage::helper('catalog')->__('Root')); 
} 

$collection = Mage::getModel('catalog/category')->getCollection() 
    ->addAttributeToSelect('name') 
    ->addAttributeToFilter('is_active', '1'); 
// Continue using $tree for any additional tree operations needed

When You Do Need a Fresh Tree Instance

If you ever need to reload the category tree (for example, after making database changes mid-request), use getResourceModel() instead of getResourceSingleton(). This creates a new instance every time, so load() will pull fresh data each time:

// First fresh tree instance
$freshTree1 = Mage::getResourceModel('catalog/category_tree')->load();

// After making changes, get another fresh instance
$freshTree2 = Mage::getResourceModel('catalog/category_tree')->load();

A Quick Best Practice

Singleton resources are designed to save system resources by reusing objects. Stick to fetching them once per request whenever possible—it aligns with Magento's architecture and avoids issues like the one you ran into.

内容的提问来源于stack exchange,提问作者SagarPPanchal

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 11:53:03