0

我已经关注了这个网站上的一些问题,但仍然无法弄清楚我的设置有什么问题。我被难住了一段时间。抱歉,如果这是一个基本错误,我对 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;

    ....
}
4

1 回答 1

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,但我建议你阅读这个链接

于 2012-09-18T04:55:09.707 回答