Searching by association’s index in Doctrine 2

I stumbled upon quite an interesting problem in Doctrine 2 with ManyToOne associations. Consider this entity:

A user can leave a comment on an article. Later, I attempt to query an article with comments made by a specific user. This is the DQL that I wrote:

This makes perfect sense, since Doctrine added a user_id to the database for me. But this DQL it throws me a semantical error: ” Comment has no field or association named user_id”.

I thought that I may have misconfigured my associations, but it wasn’t the case. I even considered that Doctrine 2 might have a bug. After searching online for over an hour, I didn’t find anyone having the same problem.

I tried something quite random. I changed “c.user_id = “user_id” to “c.user = :user_id”. It worked! It’s not intuitive, because you don’t expect a comparison between an entity and an index to work. I’m not sure whether it’s an official method, since I found nothing regarding this in the documentation. Any clarification is welcome.

Here is the final query for your reference:

5 thoughts on “Searching by association’s index in Doctrine 2

  1. Ridcully

    I think it was in Doctrine1 the same. It’s DQL and not SQL you are querying Objects. It hard to explain but in PHP you would write $comment->getUser() and not $comment->getUserId() and Doctrine does the same in DQL.

  2. @Ridcully This is not entirely correct. Although you could get the entity using $comment->getUser(), the DQL in version 1 would still allow you to use WITH c.user_id = … because foreign indexes had a more explicit role in the entity.

  3. little typo : protected $acticle; -> protected $article;

  4. @Pascal Borreli Thanks, I fixed it.

  5. Marcel Douwstra

    Thank you Anna! Was struggling to make this work.

    That DOES and DOES NOT make sense on different levels.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes:

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">