2012-01-19 19 views
14

我有一个Item实体,它与一个Category实体有ManyToOne的关系。我想让他们加入类别为id以外的字段(在这种情况下,字段名为id2)。我的模式列在下面。是否可以为JoinColumn引用“id”以外的列?

class Item { 
    /** 
    * @ORM\Id 
    * @ORM\Column(name = "id", type = "integer") 
    * @ORM\GeneratedValue(strategy = "AUTO") 
    */ 
    protected $id; 
    /** 
    * @ORM\ManyToOne(targetEntity = "Category") 
    * @ORM\JoinColumn(name = "category_id", referencedColumnName = "id2") 
    */ 
    protected $category; 
} 

class Category { 
    /** 
    * @ORM\Id 
    * @ORM\Column(name = "id", type = "integer") 
    * @ORM\GeneratedValue(strategy = "AUTO") 
    */ 
    protected $id; 
    /** 
    * @ORM\Column(name = "id2", type = "string", length = "255", unique = "true") 
    */ 
    protected $id2; 

当我尝试保存的Item我得到这个错误:

Notice: Undefined index: id2 in vendor/doctrine/lib/Doctrine/ORM/Persisters/BasicEntityPersister.php line 511

果然,当我在JoinColumn注释改变id2id,一切工作正常,但我需要的实体是通过id2连接。这可能吗?

编辑
根据官方Doctrine 2文档,我想实现的是不可能的。

It is not possible to use join columns pointing to non-primary keys. Doctrine will think these are the primary keys and create lazy-loading proxies with the data, which can lead to unexpected results. Doctrine can for performance reasons not validate the correctness of this settings at runtime but only through the Validate Schema command.

来源:http://www.doctrine-project.org/docs/orm/2.1/en/reference/limitations-and-known-issues.html

回答

7

我想学说想这些是主键,从the docs

name: Column name that holds the foreign key identifier for this relation.

,在我从您的代码示例跳出另一件事是category.id2正在类型字符串,我会至少期望它是一个整数,但它也可能需要为@JoinColumn才能正常工作。

您可以逃脱只是@Indexcategory.id2并把它作为一个字符串虽然;无论如何都值得一试。

+0

感谢您的答复缺少值主键ID。我尝试将字段类型更改为整数,并添加@Index,但它仍然无效。 – 2012-01-24 15:52:03

+0

Bah!看起来他们毕竟需要成为fks。总是有多对多的选择。 – quickshiftin 2012-01-24 16:32:00

2

只是为了报告。我能够以Many2One(非定向)关系连接非PK,但我的对象无法以正常方式加载。必须装有DQL,如:

SELECT d,u FROM DEntity d 
    JOIN d.userAccount u 

这样我停下得到错误:上....

相关问题