Var*_*arg 0 php doctrine arraycollection symfony
我有一个愿望清单实体,该实体与使用MTM学说注释的产品实体有关系。我的定义$products是Array CollectionIn Wishlist的__construct(),这就是为什么我拥有addProduct()and 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();
}
}
Run Code Online (Sandbox Code Playgroud)
在我的控制器中,我有一个尝试使用removeProduct()方法的地方。我通过以下方式使用它:
$wishlist->removeProduct($product);
Run Code Online (Sandbox Code Playgroud)
但是我收到以下错误:
警告:isset中的偏移量类型非法或为空(500 Internal Server Error)
它在行中
vendor\doctrine\collections\lib\Doctrine\Common\Collections\ArrayCollection.php at line 126
Run Code Online (Sandbox Code Playgroud)
它具有以下视图:
public function remove($key)
{
if ( ! isset($this->elements[$key]) && ! array_key_exists($key, $this->elements)) {
return null;
}
}
Run Code Online (Sandbox Code Playgroud)
同时,addProduct()效果很好。我做错了什么?如何解决这个问题?
您正在寻找的是ArrayCollection的removeElement($element)功能,而不是remove($key)功能。
如其定义所示,remove($key)函数从集合中removeElement($element)删除指定索引($ key)处的元素,而从集合中删除指定的元素(如果找到)。
由于您要删除的产品不是元素而是元素,因此应该使用removeElement($product)。
教义ArrayCollection API参考在这里
| 归档时间: |
|
| 查看次数: |
295 次 |
| 最近记录: |