在我的ZF2应用程序中,我有2个Doctrine2实体:Product
和Partner
因为在某些情况下产品不需要合作伙伴,所以产品和合作伙伴之间存在可以为空的ManyToOne关系。
如果在表单中提供了合作伙伴(下拉列表),则它有效。 但如果没有,我有这个错误:
An exception occurred while executing 'SELECT t0.id AS id1, t0.title AS title2 FROM partners t0 WHERE t0.id = ?' with params [""]:
SQLSTATE[22P02]: Invalid text representation: 7 ERROR: invalid input syntax for integer: ""`
实体:
/**
* @ORM\Entity
* @ORM\Table(name="products")
*/
class Product extends AbstractEntity
{
/* ... */
/**
* @ORM\ManyToOne(targetEntity="Partner", inversedBy="products", cascade={"persist", "merge"})
* @ORM\JoinColumn(name="partner_id", referencedColumnName="id", nullable=true)
*/
protected $partner;
/* ... */
/**
* @return Partner
*/
public function getPartner()
{
return $this->partner;
}
/**
* @param Partner $partner
*
* @return $this
*/
public function setPartner(Partner $partner)
{
$this->partner = $partner;
return $this;
}
/* ... */
}
/**
* @ORM\Entity
* @ORM\Table(name="partners")
*/
class Partner extends AbstractEntity
{
/* ... */
/**
* @ORM\OneToMany(targetEntity="Product", mappedBy="partner", cascade={"persist", "merge", "remove"})
**/
protected $products;
/* ... */
public function __construct()
{
$this->products = new ArrayCollection();
}
/* ... */
/**
* @param Product $product
*
* @return $this
*/
public function addProduct(Product $product)
{
$this->products[] = $product;
$product->setPartner($this);
return $this;
}
/**
* @param $products
*
* @return $this
*/
public function addProducts($products)
{
foreach ($products as $product)
{
$this->addProduct($product);
}
return $this;
}
/**
* @param null $products
*
* @return $this
*/
public function removeProducts($products = null)
{
if (!$products)
{
$products = $this->getProducts();
}
foreach ($products as $product)
{
if (is_object($product))
{
$this->products->removeElement($product);
}
else $this->products->remove($product);
}
return $this;
}
/**
* @return mixed
*/
public function getProducts()
{
return $this->products;
}
/**
* @param mixed $products
*
* @return $this
*/
public function setProducts($products)
{
$this->products = $products;
return $this;
}
/* ... */
}
非常感谢任何帮助。
答案 0 :(得分:1)
感谢@hkulekci的回答。
我刚刚更新了输入过滤器:
public function getInputFilterSpecification()
{
return [
'partner' => ['required' => true],
/* ... */
];
}
对此:
public function getInputFilterSpecification()
{
return [
'partner' => [
'required' => true,
'continue_if_empty' => true,
'filters' => [
['name' => 'Null']
]
],
/* ... */
];
}
答案 1 :(得分:0)
您需要允许将null
值传递给setPartner
方法
public function setPartner(Partner $partner = null)
{
$this->partner = $partner;
return $this;
}
此外,根据您的表格保护程序,您需要确保如果未选择任何合作伙伴,则应将空值转换为null
。