doctrine 2加入关联未找到

时间:2012-05-03 17:11:55

标签: php orm doctrine dql

我已经关注了本网站上的一些问题,但仍然无法弄清楚我的设置有什么问题。我被困了一段时间。对不起,如果这是一个基本错误,我仍然是Doctrine的新手。谢谢。

我得到的错误是:

Error: Class models\\Classes_users has no association named users_username...

查询是:

SELECT u FROM models\Classes_users c JOIN c.users_username u WHERE c.class_id = 1

实体:

/**
 * models\Classes_users
 *
 * @Table(name="classes_users")
 * @Entity
 */
class Classes_users
{
    ...

    /**
     * @var string $users_username
     *
     * @Id
     * @ManyToOne(targetEntity="Users", inversedBy="users_username")
     * @JoinColumn(name="users_username", referencedColumnName="users_username")
     * @Column(name="users_username", type="integer", precision=0, scale=0, nullable=false, unique=false)
     */
    private $users_username;

    ...
}



/**
 * models\Users
 *
 * @Table(name="users")
 * @Entity
 */
class Users
{
    ....

    /**
     * @var string $users_username
     * @Id
     * @OneToMany(targetEntity="Classes_users", mappedBy="users_username")
     * @Column(name="users_username", type="string")
     */
    private $users_username;

    ....
}

1 个答案:

答案 0 :(得分:2)

我不知道你想要完成什么,但我认为你的实体设计有点“奇怪”,我在这里发布一些代码供你参考:

/**
 * models\Classes_users
 *
 * @Table(name="classes_users")
 * @Entity
 */
class Classes_users
{
    ...
    /**
     * @Id
     */
    private $class_id;   // use other varible as Id

    /**
     * @ManyToOne(targetEntity="Users", inversedBy="user_usernames")
     * @JoinColumn(name="user_id", referencedColumnName="id")
     **Delect this line  =>** * @Column(name="users_username", type="integer", precision=0, scale=0, nullable=false, unique=false)  
     */
    private $user;   // change name to user, this varible is a virtual variable, only make sense in php objects, there would not be a real column in database, but a user_id column produced by Doctrine instead

    ...
}



/**
 * models\Users
 *
 * @Table(name="users")
 * @Entity
 */
class Users
{
    ....
    /**
     * @Id
     *
     */
    $private id;   // use other variable as Id


    /**
     * @var string $users_username
     * @Id
     * @OneToMany(targetEntity="Classes_users", mappedBy="user")
     **Delect this line  =>** * @Column(name="users_username", type="string")
     */
    private $user_usernames;    // suggest change name to reflect the one to many associations, this variable should be an arraycollection, and there would not be a real column in database

    public function __construct()
    {
        $this->user_usernames = new ArrayCollection();
    }

    ....
}

现在您可以将查询更改为:

SELECT u FROM models \ Users u JOIN u.user_usernames c WHERE c.class_id = 1

我不知道您是否使用Symfony,但我建议您阅读this link