简体   繁体   English

原则:在一对多关联中忽略了mappedBy的值

[英]Doctrine: Value of mappedBy ignored in OneToMany Association

I set up a simple User->Comment association in Doctrine, simple OneToMany (One User can write many Comments). 我在Doctrine中建立了一个简单的User-> Comment关联,一个简单的OneToMany(一个用户可以写很多注释)。

All works find, but i found a strange behavior of Doctrine. 所有的作品都找到了,但是我发现了教义的奇怪行为。 First some Code: 首先一些代码:

User Entity 用户实体

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

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

In User, doctrine wants a mappedBy Attribute since its the inversed Side of the association. 在“用户”中,由于其关联的反面 ,教义需要一个“ mappedBy”属性。 But as it seems, I can write anything I want as value . 但是看起来,我可以写任何我想作为值的东西 (the right value would be "user_id" i think?) (正确的值为我认为的“ user_id”吗?)

So, when is this value ever used or checked? 那么,何时使用或检查此值?

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). 它会影响实体的加载方式(在OneToMany设置fetch="EAGER" ,您会收到错误),主要是在对数据进行水化处理时将所有者设置为注释对象(在后台进行操作时,会产生更多的魔力)很难理解)。 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. 我会在学问错误跟踪器中发布一个问题,它是错误的来源,如果您拼错了字段名称,则很难调试。


You need to specify inversedBy as well: 您还需要指定inversedBy

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

It should be used when you do retrieve the value of _commentsAuthored and try to do something with it (eg, count it) 当您确实检索_commentsAuthored的值并尝试对其进行处理(例如,计数)时,应使用它

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM