Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
599 views
in Technique[技术] by (71.8m points)

symfony - Primary key of owning side as a join column

NOTE: Topic is lengthy but detailed and may come in handy if you use Doctrine2 and oneToOne relationships.

Recently I came across a problem in Doctrine:

I created User and UserData objects with oneToOne bidirectional relationship:

User:
...
  oneToOne:
    userdata:
      targetEntity: UserData
      mappedBy: user

UserData:
...
  oneToOne:
    user:
      targetEntity: User
      inversedBy: userdata

So UserData was the owning side with user_id column in it:

user: id, ...
userdata: id, user_id, ...

This created a problem, where every time you fetch a User object (Single user, collection of user or collection of other object with user joined on it) Doctrine would lazy load a UserObject for each User.

Issue described here:

Proposed solution described here:

So there are 3 ways around this:

  1. Wait and see if proposed solution is addressed in Doctrine and fixed in future releases (may not happen)
  2. Manually left join UserData to User in every query (still waste of resources, dont need UserData)
  3. Switch inverse side and make User the owning side.

I decided to go with #3. So my schema relationship now looks like this:

User:
...
  oneToOne:
    userdata:
      targetEntity: UserData
      inversedBy: user

UserData:
...
  oneToOne:
    user:
      targetEntity: User
      mappedBy: userdata

This means that my tables now look like this:

user: id, userdata_id, ...
userdata: id, ...

I decided that instead of having Userdata.id autoincremented, I'll set it manually and match it with user.id. This means that UserData.id will always match user.id.

Question Can I use user.id (a primary autoincremented key) as joinColum instead of userdata_id since they will always have the same value? Do you see any potential issues with this way of doing things?

Any other tips or opinions about this issue is greatly welcomed and appreciated.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You could also force partial objects, to get rid off lazy-loading:

use DoctrineORMQuery;

//...
$query->setHint(Query::HINT_FORCE_PARTIAL_LOAD, true);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...