Symfony ONE-TO-ONE relation

2020-08-16 02:32发布

问题:

I am new to symfony2 and have trouble to do a left join between 2 entities. I'm getting following error message, and don't know how to solve this problem:

[Semantical Error] line 0, col 69 near 'i': Error: Class Bundle\Entity\Users has no association named user_id

Entity Users:

class Users
{
    /**
     * @ORM\Id
     * @ORM\Column(name="user_id", type="string", length="16")
     * @ORM\OneToOne(targetEntity="UsersInformation", mappedBy="Users")
     */
    protected $user_id;

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


    /**
     * @ORM\Column(type="string", length="32")
     */
    protected $password;

    ...

     /**
     * Set user_id
     *
     * @param string $userId
     */
    public function setUserId($userId)
    {
        $this->user_id = $userId;
    }

    /**
     * Get user_id
     *
     * @return string 
     */
    public function getUserId()
    {
        return $this->user_id;
    }

    ...
}

Entity UsersInformation:

 class UsersInformation
  {
    /**
     * @ORM\Id
     * @ORM\Column(type="string", length="16")
     * @ORM\OneToOne(targetEntity="Users", inversedBy="UsersInformation")
     * @ORM\JoinColumn(name="user_id", referencedColumnName="user_id")
     */
    protected $user_id;

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

    /**
     * @ORM\Column(type="string", length="1")
     */
    public $gender;

    /**
     * @ORM\Column(type="string", length="255")
     */
    public $company;

    ....
  }

The UsersRepository looks like this:

public function getAllUsers($limit = null)
  {
        $qb = $this->createQueryBuilder('u')
                   ->select('u, i')
                   ->leftJoin('u.user_id', 'i');


        if (false === is_null($limit))
            $qb->setMaxResults($limit);

        return $qb->getQuery()
                  ->getResult();
   }

What I'm doing wrong?

回答1:

I think the querybuilder looks alright. Your problem is likely in the data structure.

The way you normally approach this is by setting up a property per relation. For your Users class it'd make sense to have an information or userInformation one for example.

Perhaps something like this helps?

class User
{
    /**
     * @ORM\Id
     */
    protected $id;

    /**
     * @ORM\OneToOne(targetEntity="UserInformation")
     */
    protected $information;
}

class UserInformation
{
    /**
     * @ORM\Id
     */
    protected $id;

    /**
     * @ORM\OneToOne(targetEntity="User", inversedBy="information")
     * @ORM\JoinColumn(name="user_id", referencedColumnName="id")
     */
    protected $user;
}