1

我遇到了一些麻烦Doctrine 2- 我有一个预先存在的实体Site,用数据调用(即有一些行的表),它oneToMany与一个名为User.

我的User实体与 有manyToOne关系Site

创建新用户实体时,我想将其链接到特定站点。我的代码如下:

// create entity manager instance
$em = \Doctrine\ORM\EntityManager::create($connection, $config);

// get the site ID entry i'd like to insert into this user
$site = $em->createQuery('SELECT s FROM Entity\Site s WHERE s.name = ?1')->setParameter(1, 'My Site')->getResult();

// create new user
$obj = new \Entity\User;

// associate user with site
$obj->setJoiningSite($site[0]);

$em->persist($obj);
$em->flush();
$em->clear();

现在我的问题:多次运行此代码片段会导致为每个新用户实体创建一个新站点实体,即它不使用单个现有站点,而是每次创建一个新站点。

这是我YAML文件的相关部分。第一个站点:

Entity\Site:
    type: entity
    table: sites
    id:
        id:
            type: integer
            generator:
                strategy: AUTO
    fields:
        name:
            type: string
            length: 100
    oneToMany:
        users:
            targetEntity: Entity\User
            mappedBy: site

这是User

Entity\User:
    type: entity
    table: users
    id:
        id:
            type: integer
            generator:
                strategy: AUTO
    fields:
        username:
            type: string
            length: 20
    manyToOne:
        joining_site:
            targetEntity: Entity\Site
            mappedBy: users
            cascade: ["persist"]
            joinColumn:
                name: join_site_id
                referencedColumnName: id

为什么要这样做,我怎样才能得到我正在寻找的行为?

谢谢

4

1 回答 1

1

Try using this:

$site = $em->getRepository('Entity\User')->findOneBy(array('name' => [name_of_site]));
$user = new Entity\User();
$user->setJoiningSite($site);
$em->persist($user);
$em->flush();

and your method like this:

public function setJoiningSite($site) {
    $this->site = $site;
}

You must to declare the site property as Entity\Site class.

于 2013-07-16T17:48:27.320 回答