Symfony/Doctrine:实体无效未被列出,原因何在?
doctrine:mapping:info未列出 我定义了如下实体类,但执行php bin/console doctrine:mapping:info命令时该实体未被列出,尝试过重命名实体、修改命名空间、增减字段均无法解决问题。注:另有结构相同的实体可被Doctrine正常识别。
<?php namespace App\Entity\Geo; use Doctrine\ORM\Mapping as ORM; /* * @ORM\Entity(repositoryClass="App\Repository\Geo\CityRepository") * @ORM\Table(name="geo_cities") */ class City { /** * @ORM\Id() * @ORM\GeneratedValue() * @ORM\Column(type="integer") */ protected ?int $id = null; /** * Name of the city * * @ORM\Column(type="string", length=50, nullable=false) */ protected string $name; /** * Addition for name of city * * @ORM\Column(type="string", length=20, nullable=false) */ protected ?string $name_more = null; // Setters and getters }
可能的原因及解决办法
类注释语法错误:Doctrine的注解要求使用
/** */(双星开头)的块注释,你当前的类注释是/* */(单星开头),Doctrine会忽略该注解,导致无法识别实体。修改类注释为:/** * @ORM\Entity(repositoryClass="App\Repository\Geo\CityRepository") * @ORM\Table(name="geo_cities") */字段注解与类型不匹配:
name_more字段的@ORM\Column设置了nullable=false,但属性类型是?string(允许为null),这会触发Doctrine映射验证失败。解决方式二选一:- 将
nullable=false改为nullable=true - 将属性类型改为
string,并在构造函数中初始化该字段或设置默认值
- 将
Repository类不存在或路径错误:检查
App\Repository\Geo\CityRepository是否存在,且正确继承自Symfony\Bridge\Doctrine\Repository\ServiceEntityRepository,如果Repository缺失或命名空间错误,Doctrine可能无法识别实体。Doctrine实体映射配置问题:确认
config/packages/doctrine.yaml中的实体映射路径包含App\Entity\Geo,示例配置如下:doctrine: orm: mappings: App: is_bundle: false type: annotation dir: '%kernel.project_dir%/src/Entity' prefix: 'App\Entity' alias: App该配置会扫描
src/Entity下所有子目录的实体类,确保配置正确。缓存干扰:执行
php bin/console doctrine:cache:clear-metadata清除Doctrine元数据缓存,旧缓存可能导致新实体无法被识别。
内容的提问来源于stack exchange,提问作者clem

