21

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.

2 Answers 2

32

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.

1
  • 2
    WOW, simple explanation but clear enough make us understand the concept.
    – GusDeCooL
    Commented Aug 18, 2014 at 15:29
1

Same as timdev`s answer,

Unidirectional & BiDirectional is just ORM Concepts, these have nothing to do with database, Suppose you have a OneToMany relation -

user has blogs

So you can add this to your User Entity as OneToMany Property

but obviously there exisits ManyToOne Relation

Blogs Has User

so it is optional for you to create a ManyToOne relation in your Blog Entity, If you want to access user from blog entity then add this property if you dont want then dont add,its not necessary. in both Cases (you are adding bidirectional reference or not) ORM will maintain same database structure (blog table will have user_id column) .

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.