如何在Doctrine中用YAML格式为三个类配置单表继承?
在Symfony3中配置Doctrine三类别单表继承的YAML格式
我来帮你基于已有的CustomPage实体配置,扩展出三个类的单表继承YAML配置。核心思路是:以CustomPage作为父类,另外两个类作为子类,共享同一个custom_page表,通过type字段区分不同实体类型。
第一步:完善父类CustomPage的配置
你需要在父类的YAML中添加discriminatorMap,用来映射每个实体类对应的type字段值。修改后的完整父类配置如下:
ADS\CoreBundle\Entity\CustomPage: type: entity table: custom_page inheritanceType: SINGLE_TABLE discriminatorColumn: name: type type: string # 新增:映射实体类与type字段值的对应关系 discriminatorMap: custom_page: ADS\CoreBundle\Entity\CustomPage static_page: ADS\CoreBundle\Entity\StaticPage dynamic_page: ADS\CoreBundle\Entity\DynamicPage id: id: type: bigint nullable: false options: unsigned: false id: true generator: strategy: IDENTITY fields: content: type: json_array nullable: true options: fixed: false creationdate: type: datetime nullable: true column: creationDate
第二步:配置子类实体
假设你的两个子类是StaticPage和DynamicPage,每个子类只需要指定继承父类,并定义自己独有的字段即可,无需重复表或继承类型的配置:
子类1:StaticPage
ADS\CoreBundle\Entity\StaticPage: type: entity extends: ADS\CoreBundle\Entity\CustomPage fields: staticSlug: type: string nullable: false length: 255 column: static_slug
子类2:DynamicPage
ADS\CoreBundle\Entity\DynamicPage: type: entity extends: ADS\CoreBundle\Entity\CustomPage fields: dynamicRoute: type: string nullable: false length: 255 column: dynamic_route refreshInterval: type: integer nullable: true column: refresh_interval
关键注意事项
- discriminatorMap的必要性:必须在父类中定义这个映射,键是
type字段的存储值,值是实体类的完整命名空间路径,且要包含父类自身的映射(否则查询父类时会出错)。 - 子类字段规则:子类的字段可以是必填或可选,但如果是必填的话,要注意父类实例不会有这些字段的值,所以建议要么设为nullable,要么给默认值,避免数据库约束冲突。
- 数据库表更新:配置完成后,需要执行Doctrine的schema更新命令(
php bin/console doctrine:schema:update --force)来自动添加子类字段到custom_page表中。 - 实体类定义:对应的PHP实体类也要正确继承父类,比如
StaticPage需要extends CustomPage,并添加对应的属性和getter/setter方法。
内容的提问来源于stack exchange,提问作者chouaib mehri
相关产品推荐
相关产品推荐

