Search code examples
phpsymfonyormdoctrine

inconsistent mapping in symfony


I have two entities, User and Notification. In each notification, there is a sender and receiver that are both User entities. But doctrine doesn't like it. The schema validation says:

The mappings ACME\CoreBundle\Entity\Notifications#sender and ACME\CoreBundle\Entity\User#notifications are inconsistent with each other.

Here are the mappings for both entities:

/**
 * Notifications
 *
 * @ORM\Table(name="notifications")
 * 
 */

class Notifications
{
    /**
     * @ORM\ManyToOne(targetEntity="WD\UserBundle\Entity\User", inversedBy="notifications")
     */
    protected $sender;

    /**
     * @ORM\ManyToOne(targetEntity="WD\UserBundle\Entity\User", inversedBy="notifications")
     */
    protected $receiver;
}

And the User one:

/**
 * User
 *
 * @ORM\Table(name="My_user")
 * 
 */

class User extends BaseUser
{
   /**
    * @var ArrayCollection
    *
    * @ORM\OneToMany(targetEntity="WD\CoreBundle\Entity\Notifications", mappedBy="receiver")
    * @ORM\JoinColumn(name="user_id", referencedColumnName="id")
    */
    protected $notifications;
}

For readability reasons, I did not put the whole entities code, but I believe these should be enough info. I believe the error comes from the fact I cannot put two 'mappedBy" values in User entity, but I'm not sure. And if it is, then I have no idea how to fix this. I've found kinda similar cases on this website, but none that was exactly like mine (or I haven't found them).

Any idea how I could fix this?


Solution

  • I think the issue might be that you're having two properties (sender, receiver) and using the same column to map them. If you need to distinguish between sent and received, you'll need to have sender and receiver properties on Notification and then in your user have sentNotifications and receivedNotifications. You can combine them in an un-mapped method in your User if you do need to get everything together in one call such as:

    /**
     * @var Notification[]|ArrayCollection
     */
    public function getAllNotifications()
    {
        return new ArrayCollection(
            array_merge(
                $this->sentNotifications->toArray(),
                $this->receivedNotifications->toArray()
            )
        );
    }