【问题标题】:Cannot set a NULL value in Symfony on a manyToOne association无法在 Symfony 中的 manyToOne 关联上设置 NULL 值
【发布时间】:2014-09-11 22:33:43
【问题描述】:

我正在使用 Symfony2。我正在尝试在 ManyToOne 关联上设置 NULL 值,但我不断收到此错误:

ContextErrorException:可捕获的致命错误:传递给 WIC\SettlementBundle\Entity\SettlementReport::setSupplierPayment() 的参数 1 必须是 WIC\SupplierBundle\Entity\SupplierPayment 的实例,给定 null,在 /Applications/MAMP/htdocs/ 中调用ffss/src/WIC/SupplierBundle/Controller/SupplierPaymentController.php 在第 312 行并在 /Applications/MAMP/htdocs/ffss/src/WIC/SettlementBundle/Entity/SettlementReport.php 第 342 行中定义

这是我的结算报告实体中的关联:

 /**
 * @ORM\ManyToOne(targetEntity="WIC\SupplierBundle\Entity\SupplierPayment", inversedBy="supplierReport")
 * @ORM\JoinColumn(name="supplierPayment_id", referencedColumnName="id", nullable=true)
 */
protected $supplierPayment;

这里是getter和setter方法:

 /**
 * Set supplierPayment
 *
 * @param \WIC\SupplierBundle\Entity\SupplierPayment $supplierPayment
 * @return SettlementReport
 */
public function setSupplierPayment(\WIC\SupplierBundle\Entity\SupplierPayment $supplierPayment)
{
    $this->supplierPayment = $supplierPayment;

    return $this;
}
/**
 * Get supplierPayment
 *
 * @return \WIC\SupplierBundle\Entity\SupplierPayment $supplierPayment
 */
public function getSupplierPayment()
{
    return $this->supplierPayment;
}

这是我试图设置 NULL 值的控制器:

 $settlementReport = $em->getRepository('WICSettlementBundle:SettlementReport')->find($srId);
 $settlementReport->setSupplierPayment(NULL);
 $em->flush($settlementReport);

为什么它给我这个错误,我怎样才能将值设置为 NULL?

谢谢

【问题讨论】:

  • 你的问题与 Symfony2 无关——这都是 Doctrine2。

标签: php symfony doctrine-orm


【解决方案1】:

如果您真的想允许设置 NULL(显然是这种情况),只需按如下方式更改签名:

public function setSupplierPayment
    (\WIC\SupplierBundle\Entity\SupplierPayment $supplierPayment = null)

背景:PHP 强制您传递类型转换类的对象,仅此而已;唯一的例外是 null 值,如果默认参数值也为 null。

【讨论】:

  • Omg 几年后又回到了这个问题上(我已经对答案投了赞成票)。但这不合逻辑,显然我不想学习它。
猜你喜欢
  • 2013-09-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-12-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多