【发布时间】:2018-09-18 22:38:45
【问题描述】:
我有一个 Wishlist 实体,它与使用 MTM Doctrine 注释的 Product 实体有关系。
我的定义是 $products 在 Wishlist 的 __construct() 中是 Array Collection,这就是为什么我有 addProduct() 和 removeProduct() 方法。
因此,该类具有以下视图:
<?php
namespace WishlistBundle\Entity;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping as ORM;
use ShopBundle\Entity\Product;
/**
* Wishlist
*
* @ORM\Table(name="wishlist")
* @ORM\Entity()
*/
class Wishlist
{
/**
* @var int
*
* @ORM\Column(name="id", type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* @ORM\ManyToMany(targetEntity="ShopBundle\Entity\Product")
* @ORM\JoinTable(
* name="mtm_products_in_wishlists",
* joinColumns={
* @ORM\JoinColumn(
* name="wishlist_id",
* referencedColumnName="id"
* )
* },
* inverseJoinColumns={
* @ORM\JoinColumn(
* name="product_id",
* referencedColumnName="id",
* unique=true
* )
* }
* )
*/
private $products;
...
/**
* @param Product $product
*/
public function addProduct(Product $product)
{
$this->products->add($product);
}
/**
* @param Product $product
*/
public function removeProduct(Product $product)
{
$this->products->remove($product);
}
/**
* Get products.
*
* @return string
*/
public function getProducts()
{
return $this->products;
}
/**
* Wishlist constructor.
*/
public function __construct()
{
$this->products = new ArrayCollection();
}
}
在我的控制器中,我有一个地方尝试使用removeProduct() 方法。我使用它的方式如下:
$wishlist->removeProduct($product);
但我收到以下错误:
警告:isset 中的偏移类型非法或为空(500 内部服务器错误)
它在
中的行vendor\doctrine\collections\lib\Doctrine\Common\Collections\ArrayCollection.php at line 126
它有以下视图:
public function remove($key)
{
if ( ! isset($this->elements[$key]) && ! array_key_exists($key, $this->elements)) {
return null;
}
}
同时,addProduct() 工作正常。
我做错了什么?如何解决这个问题?
【问题讨论】:
标签: php symfony doctrine arraycollection