当我插入新条目时,如果我设置 ManyToOne 关系“Category”,我将无法填写“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->name = 'yo' 而不是 $entry->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();
怎么了 ?