我正在尝试在Symfony 2项目中使用Doctrine可嵌入项。
我有一个类Purchase
,其中我有一个price
字段是可嵌入的:
/**
* Products
*
* @ORMTable(name="purchases")
* @ORMEntity
*/
class Purchase
{
/**
*
* @ORMEmbedded(class="AppBundleEntityEmbeddablePriceEmbeddable")
*/
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;
}
}
由于价格需要货币来完成,所以我有一个可嵌入的类来存储这两个值:
/**
* @ORMEmbeddable
*/
class PriceEmbeddable
{
/** @ORMColumn(type = "integer") */
private $amount;
/** @ORMColumn(type = "string") */
private $currency;
}
现在,数据库中的模式被正确创建,但是,当我持久化Purchase
实体时,我得到以下错误:
SQLSTATE[23000]: Integrity constraint violation: 1048 Column'price_amount'不能为null
我相信它:我还不明白这个机制是如何工作的。
我如何设置和获取"真实"实体(Purchase
)的值?
我将值作为Money
对象(我使用的值对象)传递给Purchase
实体中的setPrice()
方法,但是,如何将该值拆分为两个属性amount
和currency
并在可嵌入类中设置?
因为做var_dump
(使用VarDumper的dump()
函数),我以正确的方式获得实体设置:
PurchaseListener.php on line 58:
Purchase {#1795 ▼
...
-price: Money {#1000 ▼
-amount: 86
-currency: Currency {#925 ▼
-currencyCode: "EUR"
}
}
}
但是这些值没有在Embeddable中设置,我不明白为什么…
我也试图硬编码嵌入类中的值,但无论如何它不起作用,再一次,我不明白为什么:
/**
* @ORMEmbeddable
*/
class PriceEmbeddable
{
/** @ORMColumn(type = "integer") */
private $amount;
/** @ORMColumn(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
*
* @ORMTable(name="purchases")
* @ORMEntity
*/
class Purchase
{
/**
*
* @ORMEmbedded(class="AppBundleEntityEmbeddablePriceEmbeddable")
*/
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;
}
}
您必须在Purchase
构造函数中显式实例化PriceEmbeddable
:
class Purchase
{
...
function __construct() {
$this->price = new PriceEmbeddable();
}
...
}