【问题标题】:Weird issue with related entity in DoctrineDoctrine 中相关实体的奇怪问题
【发布时间】:2014-08-16 12:18:15
【问题描述】:

我在 Symfony 中使用 Doctrine2,我有以下设置:

一个项目类:

/**
 * Class Item
 *
 * @ORM\Table()
 * @ORM\Entity(repositoryClass="OneShortly\CommonBundle\Entity\ItemRepository")
 */
class Item
{
    /**
     * @ORM\ManyToOne(targetEntity="Category")
     * @ORM\JoinColumn(name="primaryCategory", referencedColumnName="foreignId")
     */
    private $primaryCategory;
}

还有一个 Category 类:

/**
 * Category
 *
 * @ORM\Table()
 * @ORM\Entity(repositoryClass="OneShortly\CommonBundle\Entity\CategoryRepository")
 */
class Category
{

    /**
     * @var integer
     *
     * @ORM\Column(name="foreignId", type="integer", unique=true)
     */
    private $foreignId;
}

现在当我这样做时:

$item = new Item();
$item->setPrimaryCategory($category);
$this->em->persist($item);
$this->em->flush();

我收到此错误:

[Symfony\Component\Debug\Exception\ContextErrorException] 注意: 未定义索引:foreignId in 主页/www/project/vendor/doctrine/orm/lib/Doctrine/ORM/Persisters/BasicEntityPersister.php 第 692 行

现在,我从各个角度查看了这个问题,但仍然看不出这段代码有什么问题。你能帮忙吗?

【问题讨论】:

    标签: php symfony doctrine-orm annotations


    【解决方案1】:

    经过更多挖掘后,我通过使用 doctrine:schema:validate 找到了自己:

    [映射] FAIL - 实体类 'Acme\CommonBundle\Entity\Item' 映射无效: * 引用的列名'foreignId'必须是目标实体类的主键列 'Acme\CommonBundle\Entity\Category'。

    [Database] FAIL - 数据库架构与当前架构不同步 映射文件。

    所以,我将外键从 foreignId 更改为 id(恰好是主键)并且它可以工作。当然,我可以只使用 foreignId 作为主键,但我意识到实际上我不需要它。

    【讨论】:

    • 这让我大吃一惊……我以为我可以链接到相关实体上的任何唯一字段,但它必须是 PK
    【解决方案2】:

    看看http://symfony.com/doc/current/book/doctrine.html#relationship-mapping-metadata

    你应该有:

    /**
     * Class Item
     *
     * @ORM\Table()
     * @ORM\Entity(repositoryClass="OneShortly\CommonBundle\Entity\ItemRepository")
     */
    class Item
    {
        /**
         * @ORM\ManyToOne(targetEntity="Category", inversedBy="items")
         * @ORM\JoinColumn(name="category_id", referencedColumnName="id")
         */
        private $primaryCategory;
    }
    

    和:

    /**
     * Category
     *
     * @ORM\Table()
     * @ORM\Entity(repositoryClass="OneShortly\CommonBundle\Entity\CategoryRepository")
     */
     class Category
     {
         /**
          * @ORM\OneToMany(targetEntity="Item", mappedBy="primaryCategory")
          */
          private $items;
     }
    

    在 ORM 中忘记 ID。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-06-28
      • 2017-08-23
      • 1970-01-01
      • 1970-01-01
      • 2022-11-19
      • 2020-01-05
      • 2017-01-19
      相关资源
      最近更新 更多