2013-05-06 95 views
-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(); 

有什麼不對?

回答

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%正確的方法,你甚至都不需要堅持新創建的類別(學說將這樣做爲你)。但手動嘗試設置category_id列是完全錯誤的做事方式。

還有一個: 不要試圖製作Doctrine2的ActiveRecord。當我從D1轉換到D2時,我正在考慮做同樣的事情,但最終認爲這是浪費時間。看起來你正在試圖創建自己的框架;不要那樣做。學習Symfony2;這並不容易,但這是值得的。

+0

謝謝你的幫助,我的問題解決了。你能告訴我爲什麼你認爲ActiveRecord是浪費時間,DataMapper更適合什麼? – Siol 2013-05-06 17:55:21

+1

對於初學者,你不需要擴展一些BaseRecord類。註釋非常酷,datamapper模式強制你思考對象而不是列。如果您首先開始寫單元測試,那麼您可以更輕鬆地學習OOP,您會驚訝於您的代碼將變得多潔。如果這還不夠好的解釋,堅持權威的論點;最好的PHP傢伙決定去DM而不是AR。 – Zeljko 2013-05-06 21:06:44