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

报告相同问题?

悬赏问题

  • ¥35 MIMO天线稀疏阵列排布问题
  • ¥60 用visual studio编写程序,利用间接平差求解水准网
  • ¥15 Llama如何调用shell或者Python
  • ¥20 谁能帮我挨个解读这个php语言编的代码什么意思?
  • ¥15 win10权限管理,限制普通用户使用删除功能
  • ¥15 minnio内存占用过大,内存没被回收(Windows环境)
  • ¥65 抖音咸鱼付款链接转码支付宝
  • ¥15 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?