Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to determine if a table relationship is bidirectional or unidirectional in Doctrine 2?

Tags:

I am in the process of upgrading from Doctrine 1.1.4 to Doctrine 2.0.6 in my Zend application.

Currently, I am working on mapping the associations between entities. In Doctrine 2's Documentation it says 'relationships maybe bidirectional or unidirectional. I am confused as to what these terms mean within the given context.

How do I determine if a relationship is unidirectional or bidirectional?

Appreciate the help.

like image 532
Mr B Avatar asked Jul 12 '11 10:07

Mr B


People also ask

What is unidirectional and bidirectional relationship in database?

A bidirectional relationship has both an owning side and an inverse side. A unidirectional relationship has only an owning side. The owning side of a relationship determines how the Persistence runtime makes updates to the relationship in the database.

Which is an example of a bidirectional relationship?

A bidirectional relationship is valid in both directions. Intersects is an example of a bidirectional relationship.

What does bidirectional relationship mean?

A bidirectional relationships mean that the flow of data is mutual between the related forms. With same example, let's assume the relationship between the Employee Profile and Manager Details is a two way or bidirectional relationship.

What is a bidirectional database?

Bidirectional replication allows synchronization of two databases, with inserts, updates, and deletes in each replicated in the other. The columns in the replicated tables must have compatible data types.


1 Answers

A relationship is bidirectional if both entities contain a reference to the other.

If you omit one of those references, it's unidirectional.

Consider a typical "posts" and "tags" schema. Typically, you'd implement a bidirectional association:

<?php  class Post {     // ...      /**       * @ManyToMany(targetEntity="Tag",inversedBy="posts")      */      protected $tags;      // ... }  class Tag {     // ...      /**      * @ManyToMany(targetEntity="Post",mappedBy="tags")      */      protected $posts      // ... } 

Now, imagine you decided you never (or rarely) needed to answer questions like "Which posts have Tag 'foo'?". You could omit the $posts association in your Tag entity, converting it to a unidirectional association, and take some load off of the ORM.

You could still answer that kind of question, but you'd have to write code to do it.

In fact, it's probably a good way to go in Posts/Tags scenario, as you wouldn't typically be adding/removing Posts from Tags. Typically, you'd add/remove tags from posts only. You'd only ever go from Tags to Posts when looking for "all posts with tag 'x'", which could be trivially implemented in a service class of some sort.

like image 94
timdev Avatar answered Oct 06 '22 01:10

timdev