学说中相关实体的奇怪问题


Weird issue with related entity in Doctrine

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

Item类

/**
 * 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 '组件ContextErrorException)注意:未定义索引:foreignId in家庭/www/项目/供应商/理论/orm/lib/理论/orm/持续程序/BasicEntityPersister.php第692行

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

经过一番挖掘,我发现自己使用了doctrine:schema:validate:

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

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

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

看看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