原则:OneToMany关联中mappedBy的值被忽略 [英] Doctrine: Value of mappedBy ignored in OneToMany Association

查看:701
本文介绍了原则:OneToMany关联中mappedBy的值被忽略的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Doctrine中设置了一个简单的User-> Comment关联,简单的OneToMany(一个用户可以写许多评论)。

I set up a simple User->Comment association in Doctrine, simple OneToMany (One User can write many Comments).

所有作品都找到,但是我发现教义奇怪的行为。首先,一些代码:

All works find, but i found a strange behavior of Doctrine. First some Code:

用户实体

/**
 * @ORM\Entity
 * @ORM\Table(name="users")
 */
class User extends EntityAbstract {
    /**
     * @var int
     * @ORM\Id
     * @ORM\Column(name="id", type="integer")
     * @ORM\GeneratedValue
     */
    protected $_id;

    /**
     * @var \Doctrine\Common\Collections\Collection
     * @ORM\OneToMany(targetEntity="Comment", mappedBy="TodayIsASunnyDay")
     *                                                  ^^^^^^^^^^^^^^^^ WTF
     */
    protected $_commentsAuthored;

    public function __construct() {
        $this->_commentsAuthored = 
            new \Doctrine\Common\Collections\ArrayCollection();
    }
}

注释实体 p>

Comment Entity

/**
 * @ORM\Entity
 * @ORM\Table(name="comments")
 */
class Comment extends EntityAbstract {
    /**
     * @var int
     * @ORM\Id
     * @ORM\Column(name="id", type="integer")
     * @ORM\GeneratedValue
     */
    protected $_id;

    /**
     * @var User
     * @ORM\ManyToOne(targetEntity="User")
     * @ORM\JoinColumn(name="user_id", referencedColumnName="id")
     *
     */
    protected $_author;
}

在用户中,doctrine需要一个它是该协会的反面。但是看来,我可以写任何我想要的值。 (正确的值将是user_id我想?)

In User, doctrine wants a mappedBy Attribute since its the inversed Side of the association. But as it seems, I can write anything I want as value. (the right value would be "user_id" i think?)

那么这个值何时被使用或检查?

So, when is this value ever used or checked?

推荐答案

是的,你是对的,在我的项目中检查 - 没有发出错误。它影响实体的加载方式( fetch =EAGER OneToMany 内设置,您将收到错误),主要是在保护数据时,将所有者方面放在一个注释对象上(在引擎盖下有更多的魔法,这是很难理解的)。我会在教条错误跟踪器中发布一个问题,如果拼写了一个字段名称,这是一个很难调试的错误源。

Yeah you're right, checked it in my project - no error is issued. It affects the way the entities are loaded (set fetch="EAGER" inside OneToMany and you'll get your error), mainly it sets the owner side on a comment object when hydrating data (there's a bit more magic going under the hood which is hard to understand). I'd post an issue in doctrine bug tracker, it's a source of errors that are hard to debug if you misspelled a field name.



您还需要指定 inversedBy

/**
 * @var User
 * @ORM\ManyToOne(targetEntity="User", inversedBy="_commentsAuthored")
 * @ORM\JoinColumn(name="user_id", referencedColumnName="id")
 *
 */
protected $_author;

当您检索 _commentsAuthored 并尝试使用它(例如,计数)

It should be used when you do retrieve the value of _commentsAuthored and try to do something with it (e.g., count it)

这篇关于原则:OneToMany关联中mappedBy的值被忽略的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆