dtmm0148603 2015-08-19 14:26
浏览 43
已采纳

Doctrine2一对一正确完成

I have an entity, say A. And another one B.

A={id,name} B={id,details}

I want a one-to-one relation. Basically for each x from A there must be exactly one y from B and the reverse. So I thought about solutions and came up with the following.

1. The id is shared.

But then basically it will be like. A={same_id,name} B={same_id,details} same_id is unique

  • B will have a foreign key for same_id to A.same_id.
  • Or A will have a foreign key for same_id to B.same_id

But I want to be able to get the details from A. Basically doing $a->getAB()->getDetails(); Which means that we need to implement 2).

But that sounds counterintuitive since that will mean, one must first create a new B entity and then create an A entity and point it to the B entity.

Which looks like B owns A - and is not what I want.

And in the reverse - if B has a foreign key to A, can I still tell A about B's existence, so I can do $a->getAB()->getDetails(); ?

2. B has another id, and A has a foreign key to it:

So it will be like: A={id,name,bId} B={bId,details} bId is unique, id is unique

But in this way - it seems like I am wasting a column for A. B won't know it's attached to A too which perhaps is a bad practice.

EDIT: But this doesn't solve any problem, just noticed I must again first create B, since any x from A needs to point to a valid y from B.

3. Is the problem about the automatic generation of my mappings?

Currently I am generating my XML mappings and entity classes from my MySQL database.

Could it be that this generation won't automatically tell A if B has a foreign key to it?

  • 写回答

1条回答 默认 最新

  • douzhaolu4839 2015-08-19 20:34
    关注

    One-To-One, Bidirectional association is what you're looking for (something like your example in point 2).
    And yes - owning is important. Please also read about the concepts of owning and inverse sides of associations.
    I'd say in your example A is the owning side - it has a name. Name is usually something more significant than details.

    There's no problem to create both Entities at the same time;

    $a = new A();
    $a->setName("Alpha");
    
    $b = new B();
    $b->setDetails("Alpha goes first");
    
    $a->setB($b);
    $em->persist($a)->flush();
    

    and both entities will be aware of the counterpart:

    $a->getB();
    $b->getA();
    

    Again - there MUST be an owning side and you must maintain the logic.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 mmocr的训练错误,结果全为0
  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀