Hassan Sardar
Hassan Sardar

Reputation: 4523

One to Many Relation In Doctrine

I have 2 Tables

  1. Users
  2. Messages

And the Structure of Tables:

Users:

enter image description here

Messages:

enter image description here

Now see there are number of users in Users Table and their messages are stored in Messages table identifying by fk_user_Id.

How can I make One-To-Many Relationship between these two tables or create this SQL Schema using Doctrine/Annotations?

Upvotes: 0

Views: 909

Answers (1)

Ankit Khedekar
Ankit Khedekar

Reputation: 924

This is a common case and i think you can easily find such examples if you would have searched.

You may refer this example

Your two entity files User.php and Message.php will look something like this

/**
 * @ORM\Entity
 * @ORM\Table(name="users")
 */
class User
{
    /**
     * @ORM\Id
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

    /**
     * @ORM\Column(type="string")
     */
    protected $username;

    /**
     * @ORM\OneToMany(targetEntity="Message", mappedBy="user")
     */
    protected $messages;
}

Message entity will look like this

    /**
     * @ORM\Entity
     * @ORM\Table(name="messages")
     */
    class Message
    {
        /**
         * @ORM\Id
         * @ORM\Column(type="integer")
         * @ORM\GeneratedValue(strategy="AUTO")
         */
        protected $id;

        /**
         * @ORM\Column(type="string")
         */
        protected $messageDescription;

        /**
         * @ORM\ManyToOne(targetEntity="User", inversedBy="messages")
         * @ORM\JoinColumn(name="fk_user_id", referencedColumnName="id")
         */
        protected $user;
}

Upvotes: 1

Related Questions