php - 忽略学说中缺失的实体

标签 php symfony doctrine-orm

我们正在将一个应用程序移植到 Symfony2,但目前仍无法使用 ORM 原则。我们的数据库中有一堆坏的外键,并且在不遇到“找不到实体”异常的情况下进行关系映射变得越来越困难。清理数据库已在路线图上,但不幸的是,这不是我们现在可以解决的问题。如果无法查找正确的实体,有什么方法可以让它只返回 null 吗?

如果我有以下关系映射:

    User:
      type: entity
      table: user
      id:
        userID:
          type: integer
          generator:
            strategy: NONE
      fields:
        contactName:
          type: string
          length: 255
          nullable: false
        contactPhone:
          type: string
          length: 255
          nullable: false
        companyName:
          type: string
          length: 255
          nullable: false
        username:
          type: string
          length: 255
          nullable: false
        password:
          type: string
          length: 255
          nullable: false
        email:
          type: string
          length: 255
          nullable: false
      manyToOne:
          address:
            targetEntity: Address
            joinColumn:
              name: addressID
              referencedColumnName: addressID
              nullable: true
              default: null



    -----------------------------------------------------

    Address:
      type: entity
      table: address
      id:
        addressID:
          type: integer
          generator:
            strategy: AUTO
      fields:
        street:
          type: string
          length: 255
          nullable: false
        street2:
          type: string
          length: 255
          nullable: false
        city:
          type: string
          length: 255
          nullable: false
        state:
          type: string
          length: 32
          nullable: false
        zip:
          type: string
          length: 10
          nullable: false
        country:
          type: string
          length: 40
          nullable: false

看起来,如果用户表中的 addressID 值不正确,我会收到“找不到实体”。通过序列化器发送时出现异常。

最佳答案

啊,这也是我们经常看到的PITA。如果您禁用了延迟加载,那么 Doctrine 可能会同时加载和补充所有链接的实体。但我猜当你尝试在 Symfony 中渲染模板/表单时,它会打开并消失。

启用延迟加载后,加载实体时不会出现错误,但是如果您随后尝试访问相关实体的属性(这将导致 Doctrine 加载它)或渲染,则会出现错误symfony 表单中的实体和表单上的字段与外部表的属性相关。

不幸的是,没有简单的方法可以阻止或捕获这种情况。我的建议是手动检查数据中是否有坏外键并清理数据,Doctrine 的延迟加载尤其不能容忍坏数据,而 Symfony 只会让情况变得更糟,如果遇到错误链接,就会出现错误 500。

关于php - 忽略学说中缺失的实体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32704216/

相关文章:

php - 切换到学说 : how to realize such query?

php - 正确的 Laravel 数据结构

php - Doctrine ORM 唯一字符串不区分大小写

php - 使用 `urlencode` 的 Symfony 4 Flex 数据库连接

mysql - 如何在 Doctrine2 中对 FROM 语句执行子查询

symfony - 未找到 'orderby' 列错误

php - joomla- 如何从页面中删除不需要的 js 文件

php - 加密解密环境变量

php - Symfony 和 Doctrine DQL 查询生成器 : how to use multiple setParameters inside if condition checks?

php - 如何在 Doctrine 中进行 LEFT JOIN ON OR