Magento 2 GraphQL中不使用ObjectManager加载目录集合报错求助
Magento 2 GraphQL解析器中“Call to a member function load() on null”错误修复方案
错误原因分析
出现该错误的核心原因是错误地直接注入Magento\Catalog\Model\Category模型实例。在Magento依赖注入体系中,模型类属于有状态对象,不能直接通过构造函数注入,必须通过对应Factory类创建实例,否则会导致实例未正确初始化,出现null值。
此外代码还存在其他问题:
- 自定义属性设置语法错误
- 返回结果键名与GraphQL Schema定义不匹配
- 冗余的模型实例加载逻辑
修复后的完整代码
1. 修改Resolver类(Model\Resolver\Setslidervalues.php)
<?php namespace [Vendor]\\[Extension]\\Model\\Resolver; use Magento\\Framework\\GraphQl\\Config\\Element\\Field; use Magento\\Framework\\GraphQl\\Exception\\GraphQlInputException; use Magento\\Framework\\GraphQl\\Query\\ResolverInterface; use Magento\\Framework\\GraphQl\\Schema\\Type\\ResolveInfo; use Magento\\Framework\\Exception\\NoSuchEntityException; use Magento\\Framework\\GraphQl\\Exception\\GraphQlNoSuchEntityException; use Magento\\Catalog\\Model\\CategoryFactory; use Magento\\Catalog\\Api\\CategoryRepositoryInterface; class Setslidervalues implements ResolverInterface{ private $categoryFactory; private $categoryRepository; public function __construct( CategoryFactory $categoryFactory, CategoryRepositoryInterface $categoryRepository ) { $this->categoryFactory = $categoryFactory; $this->categoryRepository = $categoryRepository; } public function resolve( Field $field, $context, ResolveInfo $info, array $value = null, array $args = null) { if (empty($args['slidermaincategoryid']) || empty($args['slidersubcategoryids'])) { throw new GraphQlInputException(__('Invalid parameter list.')); } try { // 通过Repository获取分类实例(符合Magento分层架构规范) $category = $this->categoryRepository->getById($args['slidermaincategoryid']); // 替换为实际的自定义属性代码 $attributeCode = 'your_custom_attribute_code'; $category->setCustomAttribute($attributeCode, $args['slidersubcategoryids']); $this->categoryRepository->save($category); return [ 'sliderstatus' => true, 'slidermessage' => __('Sub category is saved to the slider.') ]; } catch (NoSuchEntityException $e) { throw new GraphQlNoSuchEntityException(__($e->getMessage()), $e); } catch (\Exception $e) { return [ 'sliderstatus' => false, 'slidermessage' => __('An error occurred: %1', $e->getMessage()) ]; } } }
2. 关键修复点说明
- 移除错误的模型注入:删除
Category和CategoryInterface的直接注入,改用CategoryFactory和CategoryRepositoryInterface,后者是Magento推荐的分层架构操作方式。 - 修正参数校验逻辑:将
&&改为||,确保任一必填参数为空时抛出错误,符合业务逻辑。 - 修复自定义属性设置:替换占位符
[attribute_code]为实际属性代码,正确调用setCustomAttribute方法(参数为属性字符串和对应值)。 - 匹配Schema返回字段:返回结果键名改为
sliderstatus和slidermessage,与Setsubcategorysliderotpoutput类型定义完全一致。 - 使用Repository管理分类:通过
CategoryRepositoryInterface的getById和save方法操作分类,自动处理缓存与事务,比直接操作模型更安全。
额外注意事项
- 确保自定义属性
your_custom_attribute_code已在Magento后台正确创建并允许编辑。 - 执行依赖注入编译命令:
bin/magento setup:di:compile,确保新配置生效。 - 清理缓存:
bin/magento cache:clean。
内容的提问来源于stack exchange,提问作者Ekta Rathod
相关产品推荐
相关产品推荐

