dqxm14187 2013-12-04 15:38
浏览 25
已采纳

学说2一对一不按预期工作

I'm trying to do bi-directional one-to-one with doctrine.

User model

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

  /**
   * @OneToOne(targetEntity="Cart",mappedBy="user",cascade={"persist"})
   */
  public $cart;

}

Cart model

<?php
/**
 * @Entity
 * @Table(name="Cart")
 */
class Cart {
  /**
   * @Id
   * @Column(type="integer")
   * @GeneratedValue
   */
  protected $id;

  /**
   * @OneToOne(targetEntity="User",inversedBy="cart")
   * @JoinColumn(name="user_id", referencedColumnName="id")
   */
  public $user;
}

And I want to set the cart like that

<?php
$user->cart = new Cart;
$entityManager->flush();

The cart has been created, but the user_id is not set. (NULL)

What's wrong ?

(I've not created getters/setters for test)

  • 写回答

3条回答 默认 最新

  • dtcrw26206 2013-12-04 15:43
    关注

    So I did some extended testing to see what could be done.

    Your relationship code appears correct. I'd personally drop the join column annotation, as it defaults to that anyway.

    You DO need getters/setters inside each of the entities such as:

    // In User entity
    public function setCart(Cart $cart) {
        $this->cart = $cart;
    }
    
    // In Cart entity
    public function setUser(User $user) {
        $this->user = $user;
    }
    

    You also need to do something like:

    $user = new User();
    $em->persist($user);
    
    $cart = new Cart();
    $cart->setUser($user);
    $em->persist($cart);
    
    $user->setCart($cart);
    
    $em->flush();
    

    Using this snippet I was able to save two relationships to the DB and load them again. The documentation specifically states that new owners with cascade do not cascade.

    "Doctrine 2 does not cascade the persist operation to all nested entities that are new as well."

    In my example, I've specifically set and persisted both the new items. Existing parents with new cascading children don't have this problem.

    Hopefully you can use this information to figure out exactly what needs to change.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥20 用HslCommunication 连接欧姆龙 plc有时会连接失败。报异常为“未知错误”
  • ¥15 网络设备配置与管理这个该怎么弄
  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?