外键学说2实体的关联不设置值 [英] Doctrine 2 entity association does not set value for foreign key

查看:126
本文介绍了外键学说2实体的关联不设置值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到一个问题,一种学说2实体关联。
我有一个User实体和机构实体。一个机构可以采用多个用户(实体被简化为只显示我的问题)

I'm encountering a problem with a Doctrine 2 entity association. I have a User entity and an Agency entity. One Agency can employ multiple Users (the entities are simplified to show only my problem)

用户实体

/**
 * @Entity
 * @Table(name="users")
 **/
class User
{
    /**
     * @Id
     * @Column(type="integer")
     * @GeneratedValue
     * @var integer
     **/
    protected $id;

    /**
     * @ManyToOne(targetEntity="Agency", inversedBy="users"})
     * @JoinColumn(name="agency_id", referencedColumnName="id")
     * @var Agency
     */
    protected $agency;
}

机构实体

/**
 * @Entity
 * @Table(name="agencies")
 **/
class Agency
{
    /**
     * @Id
     * @Column(type="integer")
     * @GeneratedValue
     * @var integer
     **/
    protected $id;

    /**
     * @OneToMany(targetEntity="User", mappedBy="agency", cascade={"all"})
     * @JoinColumn(name="id", referencedColumnName="agency_id")
     * @var User[]
     */
    protected $users;


    /**
     * Add a user to the agency
     *
     * @param User $user
     * @return void
     */
    public function addUser(User $user) {

        $this->users[] = $user;
    }
}

当我现在用下面的code与用户一起建立一个机构,学说并没有为这导致MySQL的约束实现错误,用户的agency_id不能为空的用户agency_id。

When I now use the following code to create an agency along with a user, Doctrine does not set the agency_id for the user which results in a mysql contraint error that the user's agency_id must not be null.

// $em is the Doctrine EntityManager
$agency = new Agency;
$user = new User;
$agency->addUser($user);
$em->persist($agency);
$em->flush();

到目前为止,我发现做主义的唯一途径为用户设置的agency_id被分配机构用户额外地增加用户的机构。在我的ORM的理解它应该已经设置agency_id当用户在格兰机构的用户收集和它的beeing保存。

so far, the only way I found to make Doctrine set the agency_id for the user is assigning the agency to the user additionally to adding the user to the agency. In my understanding of an ORM it should already set the agency_id when the user is in the users collection of teh agency and it's beeing saved.

$user->agency = $agency;
$agency->addUser($user);

这有什么错或丢失我的注释/元数据?

Is there anything wrong or missing with my annotations/metadata?

推荐答案

我发现教条2文档中的内容:

I found something in the Doctrine 2 documentation:

只发到关联的反向端的变化被忽略。
  请务必更新双向关联,双方(或
  至少拥有方,从教义的角度来看)

Changes made only to the inverse side of an association are ignored. Make sure to update both sides of a bidirectional association (or at least the owning side, from Doctrine’s point of view)

作为我的情况下拥有一边是我必须更新它的用户。学说1是能够自动管理它...太糟糕了。

As in my case the owning side is the User I must update it. Doctrine 1 was able to manage it automatically... too bad.

这篇关于外键学说2实体的关联不设置值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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