Zend - doctrine 2插入数据/关联映射

时间:2011-06-29 17:08:07

标签: zend-framework doctrine doctrine-orm

我终于为我的两个表设置了映射,我现在可以通过querybuilder连接表..

但是,我无法将数据添加到连接列,它一直说空。

我的帐户实体:

namespace Entities\Users;

/**
 * @Entity(repositoryClass="\Entities\Users\Account")
 * @Table(name="account")
 * @HasLifecycleCallbacks
 */
class Account extends \Entities\AbstractEntity {

    /**
     * @Id @Column(name="accid", type="bigint",length=15)
     * @GeneratedValue(strategy="AUTO")
     */
    protected $accid;

    /** @Column(name="name", type="string", length=255) */
    protected $name;  

    /** @Column(name="profileid", type="integer", length=255) */
    protected $profileid; 


    /** @Column(name="acc_added_date", type="datetime", columnDefinition="datetime", nullable=true) */
    private $acc_added_date;

    /**
     * @ManyToOne(targetEntity="Profiledetails")
     * @JoinColumn(name="profileid", referencedColumnName="pid") 
     */
    private $account;

和我的profiledetails实体:

namespace Entities\Users;

/**
 * @Entity(repositoryClass="\Entities\Users\Profiledetails")
 * @Table(name="profiledetails")
 * @HasLifecycleCallbacks
 */
class Profiledetails extends \Entities\AbstractEntity {

    /**
     * @Id @Column(name="pid", type="bigint",length=15)
     * @GeneratedValue(strategy="AUTO")
     */
    protected $accid;
    /** @Column(name="name", type="string", length=255) */
    protected $name;
    /** @Column(name="profileid", type="integer", length=255) */
    protected $profileid;
    /** @Column(name="acc_added_date", type="datetime", columnDefinition="datetime", nullable=true) */
    private $acc_added_date;
    /**
     * @OneToMany(targetEntity="Account", mappedBy="account")
     * @JoinColumn(name="pid", referencedColumnName="pid")
     */
    private $stances;

我习惯使用:

    $postdata array ('name'=>'jason');
    $entity =new \Entities\Users\Account;
    $obj->setData($postdata);

    $this->_doctrine->persist($obj);
    $this->_doctrine->flush();
    $this->_doctrine->clear();

它并没有添加..什么方法将数据添加到父表所有链接表更新?因为之前我可以输入一个profileid,现在它是null因为我用它作为连接列..

1 个答案:

答案 0 :(得分:1)

如果在关系定义中设置cascade=[persist],则可以“更新”链接对象。您还需要为关系的两侧设置@ mappedBy和@inversedBy。基本上@mappedBy设置为oneToMany端(称为反面)和@inversedBy设置为manyToOne端(称为拥有端)

http://www.doctrine-project.org/docs/orm/2.0/en/reference/association-mapping.html#one-to-many-bidirectional

正确的方法基本上是

//assume $this->_doctrine is instance of EntityManager
$user = new User();
$user->setEmail('john@example.com');
$account = new Account();
$account->setName('john');
$account->setUser($user);
$user->addAccount($account); //if no cascade set
$this->_doctrine->persist($account); 
$this->_doctrine->persist($user); //if no cascade set
$this->_doctrine->flush();

http://www.doctrine-project.org/docs/orm/2.0/en/reference/working-with-associations.html#establishing-associations