主键和外键同时存在的原则2
我有两个表:
表 A 以 id 作为主键
表 B 以 id 作为主键和外键key
简短说明:
我需要在表 B 中有一个主键,它也是指向表 A 的主键的外键。
谁能解释一下如何通过 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;
...
但它给了我这个错误:
未捕获的异常 '学说\ORM\Mapping\MappingException' 带有消息“无标识符/主要 为实体“B”指定的密钥。每一个 实体必须有一个标识符/主要 钥匙。'在 /var/www/agr-reg-php/Doctrine/ORM/Mapping/MappingException.php:37 堆栈跟踪:
注意:我不能有复合主键。
I have the two tables :
table A with id as primary key
table B with id as primary key and foreign key
Explanation on short:
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.
Can anybody explain me how to map this by annotations in Doctrine 2?
Note:
I tried it By this :
class A
{
/**
* @var bigint $id
*
* @Column(name="id", type="bigint", nullable=false)
* @Id
* @GeneratedValue(strategy="IDENTITY")
*/
private $a_id;
...
and B table:
class B
{
/**
* @var bigint $id
* @Id
* @OneToOne(targetEntity="A", fetch="LAZY")
* @JoinColumn(name="id", referencedColumnName="id")
*/
private $b_id;
...
But it gives me this error:
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
自Doctrine 2.1以来,这是可能的:
This is possible since Doctrine 2.1:
我可以解决这个问题,创建一个与外部字段同名的 pk 字段
I could solve the problem, creating a pk field with the same name to the foreign field
我有同样的任务并通过实验找到了这个解决方案:
I had the same task and experimentaly found this solution:
最后,我通过在实体类中为真实表中的同一列指定两个字段来解决我的问题。这些更改仅在 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):
In fact all what I have done is write two fields in my entity for the same primary key and foreign key.
嗯,这是插入的另一种临时解决方案:
在具有语言中的外键和主键的类中插入
Well this is other temporal solution for insert:
this insert in a Class With the foreign key and primary key in language