无法在 Symfony 中对 manyToOne 关联设置 NULL 值

Lar*_*una 2 php symfony doctrine-orm

我正在使用 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;
Run Code Online (Sandbox Code Playgroud)

下面是 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;
}
Run Code Online (Sandbox Code Playgroud)

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

 $settlementReport = $em->getRepository('WICSettlementBundle:SettlementReport')->find($srId);
 $settlementReport->setSupplierPayment(NULL);
 $em->flush($settlementReport);
Run Code Online (Sandbox Code Playgroud)

为什么它给我那个错误,我如何将值设置为 NULL?

谢谢

lxg*_*lxg 5

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

public function setSupplierPayment
    (\WIC\SupplierBundle\Entity\SupplierPayment $supplierPayment = null)
Run Code Online (Sandbox Code Playgroud)

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