Jason Swett
Jason Swett

Reputation: 45164

Doctrine 2 many-to-one relationship not working

I have two tables in my database: user and media_contact. The media_contact table has a user_id, so, obviously, my intent is to be able to select media contacts based on a user.

The problem I'm having is that this fails:

// VNN/PressboxBundle/Entity/User.php
// $this in this case is a User object with id 26
$customContacts = $em->getRepository('VNNPressboxBundle:MediaContact')->findByUser($this);

This gives me nothing. $customContacts is empty. But:

mysql> select * from media_contact where user_id=26;
+-----+-------------+-----------------------+---------------+---------+
| id  | name        | email                 | media_area_id | user_id |
+-----+-------------+-----------------------+---------------+---------+
| 177 | Jason Swett | [email protected] |          NULL |      26 |
| 183 | Sam         | [email protected]           |          NULL |      26 |
+-----+-------------+-----------------------+---------------+---------+
2 rows in set (0.00 sec)

It should really be returning two objects. I really don't understand why this is happening.

Here are my annotations:

// User.php

/** 
 * @ORM\OneToMany(targetEntity="MediaContact", mappedBy="user")
 */
private $mediaContacts;

-

// MediaContact.php
/** 
 * @ORM\ManyToOne(targetEntity="User", inversedBy="mediaContacts")
 * @ORM\JoinColumn(name="user_id", referencedColumnName="id")
 */
private $user;

What could be going wrong?

Upvotes: 1

Views: 1811

Answers (1)

Juan Sosa
Juan Sosa

Reputation: 5280

You have to use $this->getId() instead of $this in order for it to work:

$customContacts = $em->getRepository('VNNPressboxBundle:MediaContact')->findByUser($this->getId());

Upvotes: 1

Related Questions