当设置ManyToOne关系时,Doctrine 2 category_id始终为NULL

时间:2013-05-06 12:09:47

标签: doctrine-orm

当我插入新条目时如果我设置ManyToOne关系“类别”我将无法填写“categoryId”字段为什么?

这是具有关系的实体:

<?php

namespace Application\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * Item
 *
 * @ORM\Table(name="item")
 * @ORM\Entity
 */
class Item extends Base
{
    /**
     * @ORM\ManyToOne(targetEntity="Category")
     */
    private $category;


    /**
     * @var integer
     *
     * @ORM\Column(name="id", type="integer", nullable=false)
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="IDENTITY")
     */
    public $id;

    /**
     * @var string
     *
     * @ORM\Column(name="name", type="string", length=40, nullable=false)
     */
    public $name;

    /**
     * @var integer
     *
     * @ORM\Column(name="category_id", type="integer", nullable=true)
     */
    public $categoryId;

}

这是我用于生成getter和setter的基类,并允许$ entry-&gt; name ='yo'而不是$ entry-&gt; setName('yo');

<?php

namespace Application\Entity;

class Base
{
    public function __call($method, $args) {
        if (preg_match('#^get#i', $method)) {
            $property = str_replace('get', '', $method);
            $property = strtolower($property);
            return $this->$property;
        }

        if (preg_match('#^set#i', $method)) {
            $property = str_replace('set', '', $method);
            $property = strtolower($property);
            $this->$property = $args[0];
        }
    }

    public function fromArray(array $array = array()) {
        foreach ($array as $key => $value) {
            $this->$key = $value; 
        }
    }
}

这是我保存新项目的方式:

$item = new \Application\Entity\Item();
$item->name = 'Computer';
$item->categoryId = '12';
$this->em->persist($item);
$this->em->flush();

有什么问题?

1 个答案:

答案 0 :(得分:1)

你做错了!使用Doctrine,您不能使用category_id列(和类似的)但使用关系。学说将处理专栏。

您必须阅读文档,但正确的方法是:

$category = new Category() ;
$category->setName("Food") ;

$item = new Item() ;
$item->setName("Pizza") ;
$item->setCategory($category) ;

$em->persist($item) ;
$em->flush() ;

这是100%正确的做事方式,你甚至不需要坚持新创建类别(Doctrine会为你做到这一点)。但手动尝试设置category_id列是完全错误的做事方式。

还有一个: 不要试图制作Doctrine2的ActiveRecord。当我从D1切换到D2时,我正在考虑做同样的事情,但最后,认为这是浪费时间。看起来你正在尝试制作自己的框架;不要那样做。学习Symfony2;这不容易,但值得花时间。

相关问题