Doctrine orm 1:m关系:保存订单而不同时保存新的付款方式?
我在下面有这些实体。他们之间有1:m的关系 MetodoPago是一种付款方式,已经保存在数据库中:信用卡、现金等,Pedido是订单 现在我想将付款方式与订单关联,因此我有以下代码:Doctrine orm 1:m关系:保存订单而不同时保存新的付款方式?,doctrine-orm,doctrine,Doctrine Orm,Doctrine,我在下面有这些实体。他们之间有1:m的关系 MetodoPago是一种付款方式,已经保存在数据库中:信用卡、现金等,Pedido是订单 现在我想将付款方式与订单关联,因此我有以下代码: $pedido = new Pedido(); $repositoryMetodoPago = $this->getDoctrine()->getRepository('ProjectBackendBundle:MetodoPago'); $metodoPago = $repositoryMetod
$pedido = new Pedido();
$repositoryMetodoPago = $this->getDoctrine()->getRepository('ProjectBackendBundle:MetodoPago');
$metodoPago = $repositoryMetodoPago->find(1);
$pedido->setMetodoPago($metodoPago);
$em = $this->getDoctrine()->getManager();
$em->persist($pedido);
$em->flush();
此代码的问题是:在保存新订单的同时,还保存了一个新的MetodoPago!!我对此很感兴趣,因为我已经保存了所有可用的付款方式
我的尝试:我尝试过这个setter:
public function setMetodoPago(\Project\BackendBundle\Entity\MetodoPago $metodoPago = null)
{
$this->metodoPago = $metodoPago->getId();
return $this;
}
但是当我尝试运行上面的代码时,我得到了
Warning: spl_object_hash() expects parameter 1 to be object, integer given in /vendor/doctrine/orm/lib/Doctrine/ORM/UnitOfWork.php line 1389
苏欧。。我该怎么办??这些是实体:
class Pedido
{
/**
* @ORM\Id
* @ORM\Column(type="integer")
* @ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* @ORM\ManyToOne(targetEntity="MetodoPago", cascade={"persist", "remove"})
* @ORM\JoinColumn(name="metodo_pago_id", referencedColumnName="id")
**/
private $metodoPago;
/**
* Get id
*
* @return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set metodoPago
*
* @param \Project\BackendBundle\Entity\MetodoPago $metodoPago
* @return Pedido
*/
public function setMetodoPago(\Project\BackendBundle\Entity\MetodoPago $metodoPago = null)
{
var_dump($metodoPago);
$this->metodoPago = $metodoPago;
return $this;
}
/**
* Get metodoPago
*
* @return \Project\BackendBundle\Entity\MetodoPago
*/
public function getMetodoPago()
{
return $this->metodoPago;
}
}
class MetodoPago
{
/**
* @ORM\Id
* @ORM\Column(type="integer")
* @ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* @ORM\Column(type="string", name="nombre")
*/
protected $nombre;
/**
* @ORM\Column(type="float", name="precio")
*/
protected $precio;
/**
* Get id
*
* @return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set nombre
*
* @param string $nombre
* @return MetodoPago
*/
public function setNombre($nombre)
{
$this->nombre = $nombre;
return $this;
}
/**
* Get nombre
*
* @return string
*/
public function getNombre()
{
return $this->nombre;
}
/**
* Set precio
*
* @param float $precio
* @return MetodoPago
*/
public function setPrecio($precio)
{
$this->precio = $precio;
return $this;
}
/**
* Get precio
*
* @return float
*/
public function getPrecio()
{
return $this->precio;
}
}
你考虑过添加一个双向关系吗?@fkup不,那会解决我的问题吗?也许。我不是专家,但我在应用程序中只使用双向关系,我没有这种问题。否则,您的代码似乎是正确的。我可以看到另一种解决方法,但不确定它是否是最佳解决方案。您可以在Pedido上同时映射metodoPago和metodo_pago_id,因此当您坚持一个新的Pedido时,只需设置metodo_pago_id而不是metodoPago。当你从数据库中得到一个Pedido时,它也会包含metodoPago,因为它被映射了。