Search code examples
symfonyentitypostsrelationships

Symfony2 Entities: Many-To-One relationship between user and posts


How can I add relationship between user and posts using users id? I saw some examples, but I couldn't follow what inversedBy and mappedBy are for... Is it possible to store profile_id and not the object?

User profile entity:

class Profiles
{

/**
 * @var integer
 *
 * @ORM\Column(name="id", type="integer")
 * @ORM\Id
 * @ORM\GeneratedValue(strategy="AUTO")
 */
private $id;

/**
 * @var string
 *
 * @ORM\Column(name="email", type="string", length=255)
 */
private $email;

/**
 * @var string
 *
 * @ORM\Column(name="password", type="string", length=255)
 */
private $password;

Posts/Comments entity:

class Comments
{

/**
 * @var integer
 *
 * @ORM\Column(name="id", type="integer")
 * @ORM\Id
 * @ORM\GeneratedValue(strategy="AUTO")
 */
private $id;

/**
 * @var Profiles
 *
 * @ORM\ManyToOne(targetEntity="Profiles")
 * @ORM\JoinColumn(name="profile_id", referencedColumnName="id")
 */
private $profile;

Solution

  • OK example

    ///User Enity

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

    // Car Entity

      /**
       * @ORM\ManyToOne(targetEntity="User", inversedBy="cars")
       * @ORM\JoinColumn(name="users_id", referencedColumnName="id")
       */
    private $user;
    

    So it sill take the user id and populate this against the Car users_id column in that record

    So meaning the a user can be associated to many cars