2015-08-28 91 views
1

我想在Symfony 2項目中使用Doctrine embeddables。如何使用Doctrine Embeddables

我有一個類Purchase在那裏我有一個price字段是嵌入:

/** 
* Products 
* 
* @ORM\Table(name="purchases") 
* @ORM\Entity 
*/ 
class Purchase 
{ 
    /** 
    * 
    * @ORM\Embedded(class="AppBundle\Entity\Embeddable\PriceEmbeddable") 
    */ 
    private $price; 

    /** 
    * Set price 
    * 
    * @param MoneyInterface $price 
    * @return $this 
    */ 
    public function setPrice(MoneyInterface $price) 
    { 
     $this->price = $price; 

     return $this; 
    } 

    /** 
    * Get price 
    * 
    * @return MoneyInterface|float 
    */ 
    public function getPrice() 
    { 
     return $this->price; 
    } 

} 

其價格需要一個貨幣是完整的,所以我有存儲這兩個值嵌入類:

現在
/** 
* @ORM\Embeddable 
*/ 
class PriceEmbeddable 
{ 
    /** @ORM\Column(type = "integer") */ 
    private $amount; 

    /** @ORM\Column(type = "string") */ 
    private $currency; 
} 

,在數據庫中的模式是正確創建,但是,當我堅持了Purchase實體,我得到以下錯誤:

SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'price_amount' cannot be null

我相信它:我還沒有理解機制如何工作。

我如何設置並從「真實」實體(Purchase)獲取值?

我傳遞值作爲一個Money對象(a value object I use)的方法setPrice()Purchase實體,但是,該值是如何分裂成兩個屬性amountcurrency並在嵌入類設置?

因爲做一個var_dump(使用VarDumperdump()功能)我得到實體集的正確方法:

PurchaseListener.php on line 58: 
Purchase {#1795 ▼ 
    ... 
    -price: Money {#1000 ▼ 
    -amount: 86 
    -currency: Currency {#925 ▼ 
     -currencyCode: "EUR" 
    } 
    } 
} 

但是,這些值不會在嵌入設置,我不明白爲什麼...

我也試過硬編碼嵌入類中的值,但無論如何它不工作,並且,我不明白爲什麼:

/** 
* @ORM\Embeddable 
*/ 
class PriceEmbeddable 
{ 
    /** @ORM\Column(type = "integer") */ 
    private $amount; 

    /** @ORM\Column(type = "string") */ 
    private $currency; 

    public function __construct($value) 
    { 
     $this->currency = 'EUR'; 
     $this->amount = 90; 
    } 

    public function setAmount($amount) 
    { 
     $this->amount = $amount = 90; 
    } 

    public function setCurrency($currency) 
    { 
     $this->currency = $currency = 'EUR'; 
    } 

    public function getAmount() 
    { 
     return $this->amount; 
    } 

    public function getCurrency() 
    { 
     return $this->currency; 
    } 
} 

回答

0

這是簡單的解決辦法:

/** 
* Products 
* 
* @ORM\Table(name="purchases") 
* @ORM\Entity 
*/ 
class Purchase 
{ 
    /** 
    * 
    * @ORM\Embedded(class="AppBundle\Entity\Embeddable\PriceEmbeddable") 
    */ 
    private $price; 

    /** 
    * Set price 
    * 
    * @param PriceEmbeddable $price 
    * @return $this 
    */ 
    public function setPrice(PriceEmbeddable $price) 
    { 
     $this->price = $price; 

     return $this; 
    } 

    /** 
    * Get price 
    * 
    * @return PriceEmbeddable 
    */ 
    public function getPrice() 
    { 
     return $this->price; 
    } 

}