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

EasyAdmin 4关联字段报错:get_class()参数应为对象而非字符串

解决EasyAdmin关联字段配置报错问题

错误现象

配置EasyAdmin关联字段时触发以下错误:

TypeError:
get_class(): Argument #1 ($object) must be of type object, string given

  at
vendor\doctrine\common\src\Util\ClassUtils.php:57
  at Doctrine\Common\Util\ClassUtils::getClass()

若省略configureFields方法,type字段不显示;改用Field::new('type')则出现:

The Doctrine type of the "type" field is "2", which is not supported by EasyAdmin. For Doctrine's Custom Mapping Types have a look at EasyAdmin's field docs.

问题根源

News实体中,type字段被错误定义为string类型,但它是ManyToOne关联字段,实际应对应TypeDictionary实体对象。类型不匹配导致Doctrine和EasyAdmin无法正确处理关联关系,进而抛出类型错误。

修复方案

1. 修正News实体的type字段定义

将字段类型从string改为?TypeDictionary(允许空值,若需强制非空可添加#[ORM\JoinColumn(nullable: false)]),同时更新对应的getter/setter方法:

// src/Entity/News.php
namespace App\Entity;

// 保留原有use语句,新增TypeDictionary引用
use App\Entity\TypeDictionary;

class News
{
    // 保留其他字段定义

    #[ORM\ManyToOne(targetEntity: TypeDictionary::class)]
    #[ORM\JoinColumn(name: 'type_id', referencedColumnName: 'id')]
    private ?TypeDictionary $type = null;

    // 保留其他方法

    public function setType(?TypeDictionary $type): News
    {
        $this->type = $type;
        return $this;
    }

    public function getType(): ?TypeDictionary
    {
        return $this->type;
    }

    // 保留其他方法
}

2. 保留NewsCrudController的关联字段配置

原AssociationField::new('type')的配置是正确的,无需修改:

// src/Controller/Admin/NewsCrudController.php
public function configureFields(string $pageName): iterable
{
    return [
        AssociationField::new('type'),
        TextField::new('title'),
        TextField::new('url'),
        DateField::new('date'),
        TextField::new('displayLocation'),
    ];
}

验证

修改后重新运行项目,EasyAdmin的News管理页面将正常加载type关联字段的选择器,不再触发错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.05 14:45:27