【问题标题】:Doctrine, editing ManyToMany - Indirect modification of overloaded property教义,编辑 ManyToMany - 重载属性的间接修改
【发布时间】:2015-03-09 14:41:15
【问题描述】:

假设我有这样的东西

class Menu extends \Kdyby\Doctrine\Entities\BaseEntity {

/**
 * @ORM\ManyToMany(targetEntity="MenuItem", mappedBy="menus")
 **/
protected $menuItems;

function __construct() {
    $this->menuItems = new \Doctrine\Common\Collections\ArrayCollection();
}
}

还有这个

class MenuItem extends \Kdyby\Doctrine\Entities\BaseEntity {
/**
 * @ORM\ManyToMany(targetEntity="Menu", inversedBy="menuItems")
 * @ORM\JoinTable(name="cms_menuMenuItems")
 */
protected $menus;

public function __construct() {
    $this->menus = new \Doctrine\Common\Collections\ArrayCollection();
}

现在当我想在代码中做这样的事情时

$menu->menuItems->add( $menuItem );

我收到关于 $menu->menuItems 不是对象的错误(当我转储菜​​单时,它说 menuItems 属性是 PersistendCollection) 当我转储 $menu->menuItems 时,我发现 $menuItems 属性是一个数组。好的,那我想推进去

$menu->menuItems[] = $menuItem;

但没有任何反应,我收到以下 PHP 通知: 间接修改重载属性

【问题讨论】:

    标签: php orm doctrine many-to-many


    【解决方案1】:

    请记住,您将 $menuItems 声明为 protected。要访问它,您应该创建一个 getter(如果您在类之外调用它,您没有指定,但我猜它):

    public function getMenuItems() {
        return $this->menuItems;
    }
    

    然后添加一个MenuItem:

    $menu->getMenuItems()->add($item);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-05-16
      • 1970-01-01
      • 2012-03-02
      • 2020-03-24
      • 2011-07-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多