dongmi1872 2014-05-27 12:00
浏览 37

OneToMany关系无法获取ID

I have two entities (Item and Products).

One item has only one product. One product could have 0 or N items.

When I Create a new Item, all is right except product_id is null, but in dev environment product_id is right.

class Item{
/**
 * @var integer
 *
 * @ORM\Column(name="id", type="integer", nullable=false)
 * @ORM\Id
 * @ORM\GeneratedValue(strategy="IDENTITY")
 */
protected $id;    

/**
 * @ORM\ManyToOne(targetEntity="Products", inversedBy="item", cascade={"persist"})
 * @ORM\JoinColumn(name="product_id", referencedColumnName="product_id", onDelete="cascade")
 * @var My\WebBundle\Entity\Products
 */  
protected $products;  

 /**
 * Get Id
 *
 * @return integer 
 */
public function getId()
{
    return $this->id;
}

/**
* Set products
* 
* @param My\WebBundle\Entity\Products $products
*/
public function setProducts(\My\WebBundle\Entity\Products $products)
{
    $this->products = $products;

    return $this;
}

/**
* get products
* 
* @return My\WebBundle\Entity\Products
*/
public function getProducts()
{
    return $this->products;
}

}

Class Product

class Products
{
/**
 * @var integer
 *
 * @ORM\Column(name="product_id", type="integer", nullable=false)
 * @ORM\Id
 * @ORM\GeneratedValue(strategy="IDENTITY")
 */
protected $productId;

/**
* @ORM\OneToMany(targetEntity="Item", mappedBy="products", cascade={"persist", "remove"})
*/
protected $item;

/**
 * Get productId
 *
 * @return integer 
 */
public function getProductId()
{
    return $this->productId;
}

public function addItem(\My\WebBundle\Entity\Item $item)
{
    $this->item[] = $item;
    $item->setProducts($this);
    return $this;
}

/**
 * Get item
 *
 * @return Doctrine\Common\Collections\Collection
 */
public function getItem()
{
    return $this->item;
}
}

My problem is this, when I create this Item I use:

$p = $em->getRepository('MyWebBundle:Products')->findOneByCode($code);                
$item->setProducts($p);  

In my database, in Item table, product_id is null, but if I do this in dev environment product_id is right.

Anybody have any idea? Thanks in advance.

---edit--- I have a simple controller like this:

$em = $this->getDoctrine()->getManager();
$item = new Item();
$item->setName($name);
$p = $em->getRepository('MyWebBundle:Products')->findOneByCode($product);                
$item->setProducts($p); 
$em->persist($item);
$em->flush()
  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥15 keil的map文件中Image component sizes各项意思
    • ¥30 BC260Y用MQTT向阿里云发布主题消息一直错误
    • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
    • ¥15 划分vlan后,链路不通了?
    • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
    • ¥15 Vue3 大型图片数据拖动排序
    • ¥15 Centos / PETGEM
    • ¥15 划分vlan后不通了
    • ¥20 用雷电模拟器安装百达屋apk一直闪退
    • ¥15 算能科技20240506咨询(拒绝大模型回答)