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条)

报告相同问题?

悬赏问题

  • ¥15 单通道放大电路的工作原理
  • ¥30 YOLO检测微调结果p为1
  • ¥20 求快手直播间榜单匿名采集ID用户名简单能学会的
  • ¥15 DS18B20内部ADC模数转换器
  • ¥15 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题