如何使用Doctrine Embeddables
问题描述:
我想在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
实体,但是,该值是如何分裂成两个属性amount
和currency
并在嵌入类设置?
因为做一个var_dump
(使用VarDumper的dump()
功能)我得到实体集的正确方法:
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;
}
}
答
这是简单的解决办法:
/**
* 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;
}
}