我试图在Symfony 2项目中使用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]:完整性约束违规:1048列 ' price_amount'不能为空
我相信它:我还没有理解这种机制是如何运作的。
我如何设置和获取"真实"实体(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"
}
}
}
但是这些值未在Embeddable 中设置,我不明白为什么......
我也试图对嵌入式课程中的值进行硬编码,但无论如何它都不起作用,而且,我不明白为什么:
/**
* @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 :(得分: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;
}
}
答案 1 :(得分:0)
您必须在 PriceEmbeddable
构造函数中显式实例化 Purchase
:
class Purchase
{
...
function __construct() {
$this->price = new PriceEmbeddable();
}
...
}