Symfony 3,ArrayCollection的remove()导致错误“警告:isset中的偏移量类型为非法或为空”

Var*_*arg 0 php doctrine arraycollection symfony

我有一个愿望清单实体,该实体与使用MTM学说注释的产品实体有关系。我的定义$productsArray 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()效果很好。我做错了什么?如何解决这个问题?

iii*_*rxs 5

您正在寻找的是ArrayCollection的removeElement($element)功能,而不是remove($key)功能。

如其定义所示,remove($key)函数从集合中removeElement($element)删除指定索引($ key)处的元素,而从集合中删除指定的元素(如果找到)。

由于您要删除的产品不是元素而是元素,因此应该使用removeElement($product)

教义ArrayCollection API参考在这里

  • 非常感谢你。这样可行。为什么它们在add()和removeElement()之间有如此大的区别?用`addElement()`和`removeElement()`来代替这样的混淆不是更合乎逻辑吗... (2认同)