-2
當我插入新條目時,如果我設置ManyToOne關係「類別」,我將無法填充「categoryId」字段爲什麼?Doctrine 2 category_id設置ManyToOne時總是NULL
這與關係的實體:
<?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和允許$入門>名=的「喲」代替$入門>的setName( '喲');
<?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();
有什麼不對?
謝謝你的幫助,我的問題解決了。你能告訴我爲什麼你認爲ActiveRecord是浪費時間,DataMapper更適合什麼? – Siol 2013-05-06 17:55:21
對於初學者,你不需要擴展一些BaseRecord類。註釋非常酷,datamapper模式強制你思考對象而不是列。如果您首先開始寫單元測試,那麼您可以更輕鬆地學習OOP,您會驚訝於您的代碼將變得多潔。如果這還不夠好的解釋,堅持權威的論點;最好的PHP傢伙決定去DM而不是AR。 – Zeljko 2013-05-06 21:06:44