【问题标题】:Using YAML to define one to many relationship使用 YAML 定义一对多关系
【发布时间】:2014-02-13 23:38:28
【问题描述】:

我承担了一个基于 YAML 的学说映射的项目。

我需要在两个实体之间创建一对多关系:帖子和图像(帖子可以有零个或任意数量的图像)。

在 Post.orm.yml 下:

TEST\Bundle\BlogBundle\Entity\Post:
    type: entity
    table: null
    fields:
        id:
            type: integer
            id: true
            generator:
                strategy: AUTO
        postUserId:
            type: integer
            column: post_user_id
        postDate:
            type: datetime
            column: post_date
        postContent:
            type: text
            column: post_content
        postTitle:
            type: string
            length: 255
            column: post_title
        commentStatus:
            type: boolean
            column: comment_status   
    oneToMany:
       images:
         targetEntity: Image
         mappedBy: pos
    lifecycleCallbacks: {  }

Image.orm.yml 下

TEST\Bundle\BlogBundle\Entity\Image:
    type: entity
    table: null
    fields:
        id:
            type: integer
            id: true
            generator:
                strategy: AUTO
        filePersistencePath:
            type: string
        subDir:
            type: string
    manyToOne:
      pos:
        targetEntity: Post
        inversedBy: images
      joinColumn:
        referencedColumnName: id

    lifecycleCallbacks: {  }

问题: 当我更新数据库架构时,出现以下错误:

 [Symfony\Component\Debug\Exception\ContextErrorException]
 Notice: Undefined index: targetEntity in C:\xampp\htdocs\bghitn\vendor\doct
 rine\orm\lib\Doctrine\ORM\Mapping\Driver\YamlDriver.php line 399

我不明白这条信息。我们总是感谢您的帮助。

编辑:这是使用 --dump-sql 更新架构的结果

C:\xampp\htdocs\bghitn>php app/console doctrine:schema:update --dump-sql
ALTER TABLE image ADD CONSTRAINT FK_C53D045F4B89032C FOREIGN KEY (post_id) REFER
ENCES post (id);
CREATE INDEX IDX_C53D045F4B89032C ON image (post_id)

【问题讨论】:

  • 仅供参考,我有几乎相同的 yml,它适用于我。您可以尝试在 pos 和 targetEntity 之前添加 2 个空格以尊重文件的空格数吗?您也可以尝试填写“表格”字段,即使我认为它不能解决问题
  • @goto:我尝试了您的建议,但不幸的是它不起作用。感谢您的宝贵时间。
  • 不要只在 targetEntity 字段中提及实体名称,而是提供实体的完整路径。另外,在删除这些实体的表后尝试更新架构

标签: php symfony doctrine-orm mapping yaml


【解决方案1】:

从 post 实体中移除 oneToMany 关系,并在 image 实体中保留 manyToOne 关系

manyToOne:
  post:
    targetEntity: TEST\Bundle\BlogBundle\Entity\Post
    joinColumn:
      name: post_id
      referencedColumnName: id

注意缩进。

【讨论】:

  • 谢谢@Praveesh。我是否应该明白,在关系数据库中,我只需要在一侧(父母或孩子)指定一对多关系,而不是两侧? PS:我在实施您的解决方案时仍然遇到问题。
  • 我现在执行“ALTER TABLE image ADD CONSTRAINT FOREIGN KEY (post_id) REFERENCES Post (id)”时发生异常:=SQLSTATE[23000]:完整性约束违规:1452 无法添加或更新子行:外键约束失败。你知道可能是什么原因吗?感谢您的宝贵时间
  • 如果您尝试同时生成这两个实体,则可能会发生错误。请先尝试生成 Post 实体,然后再生成图片实体
  • 我只是在更新数据库架构,实体已经生成了。
  • 我解决了 Praveesh 的问题。我通过 phpmyadmin 从数据库中删除了 post_id 列,然后我执行了 update-schema。
猜你喜欢
  • 1970-01-01
  • 2011-03-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多