本文介绍了Symfony ONE-TO-ONE关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是symfony2的新手,并且有麻烦在两个实体之间进行左连接。我收到以下错误消息,不知道如何解决这个问题:

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:

实体用户:

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;
    }

    ...
}

实体用户信息:

 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;

    ....
  }

UsersRepository看起来像这个:

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();
   }

我做错了什么?

推荐答案

我认为querybuilder看起来不错。您的问题可能在数据结构中。

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

通常情况下,通过设置每个关系的属性。对于您的用户类,有一个信息 userInformation 一个例如。

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.

这可能有助于帮助?

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;
}

这篇关于Symfony ONE-TO-ONE关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-29 10:34