主键和外键同时与教义2 [英] Primary key and foreign key at the same time with doctrine 2
问题描述
我有两个表格:
表 A 以 id 为主键
表 B 以 id 为主键和外键
说明简而言之:
我需要在表 B 中有一个主键,也是一个外键,指向表 A
I need to have in table B a primary key that also to be a foreign key that points to table A's primary key.
有没有人可以解释我如何通过Doctrine 2中的注释来映射这个?
Can anybody explain me how to map this by annotations in Doctrine 2?
注意:
我尝试过这样:
class A
{
/**
* @var bigint $id
*
* @Column(name="id", type="bigint", nullable=false)
* @Id
* @GeneratedValue(strategy="IDENTITY")
*/
private $a_id;
...
和 B :
class B
{
/**
* @var bigint $id
* @Id
* @OneToOne(targetEntity="A", fetch="LAZY")
* @JoinColumn(name="id", referencedColumnName="id")
*/
private $b_id;
...
但它给我这个错误:
未捕获的异常
'Doctrine\ORM\Mapping\MappingException'
与消息'无标识符/主
键指定为实体'B'。每个
实体必须有一个标识符/主要
密钥。
/var/www/agr-reg-php/Doctrine/ORM/Mapping/MappingException.php:37
堆栈跟踪:
Uncaught exception 'Doctrine\ORM\Mapping\MappingException' with message 'No identifier/primary key specified for Entity 'B'. Every Entity must have an identifier/primary key.' in /var/www/agr-reg-php/Doctrine/ORM/Mapping/MappingException.php:37 Stack trace:
注意:我不能有复合主键。
N.B: I must not have composite primary key.
推荐答案
最后,我通过在实体类中为实际表中的同一列指定两个字段来解决我的问题。更改仅在B类中(请查看A类的问题):
Finally I resolved my problem by specifying two fields in my entity class for the same column from real table. The changes are made only in class B (look at the question for class A):
class B
{
/**
* @var bigint $id
* @Id @Column(name="id", type="bigint", nullable="false")
*/
private $b_id;
/**
* @OneToOne(targetEntity="A", fetch="LAZY")
* @JoinColumn(name="id", referencedColumnName="id")
*/
private $a;
...
其实我所做的都是写二相同主键和外键的实体中的字段。
In fact all what I have done is write two fields in my entity for the same primary key and foreign key.
这篇关于主键和外键同时与教义2的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!