Aer*_*dir 5 embeddable doctrine-orm
我正在尝试在 Symfony 2 项目中使用 Doctrine embeddables。
\n\n我有一堂课Purchase,其中有一个price可嵌入的字段:
/**\n * Products\n *\n * @ORM\\Table(name="purchases")\n * @ORM\\Entity\n */\nclass Purchase\n{\n /**\n *\n * @ORM\\Embedded(class="AppBundle\\Entity\\Embeddable\\PriceEmbeddable")\n */\n private $price;\n\n /**\n * Set price\n *\n * @param MoneyInterface $price\n * @return $this\n */\n public function setPrice(MoneyInterface $price)\n {\n $this->price = $price;\n\n return $this;\n }\n\n /**\n * Get price\n *\n * @return MoneyInterface|float\n */\n public function getPrice()\n {\n return $this->price;\n }\n\n}\nRun Code Online (Sandbox Code Playgroud)\n\n由于价格需要货币才能完整,因此我有存储这两个值的嵌入类:
\n\n/**\n * @ORM\\Embeddable\n */\nclass PriceEmbeddable\n{\n /** @ORM\\Column(type = "integer") */\n private $amount;\n\n /** @ORM\\Column(type = "string") */\n private $currency;\n}\nRun Code Online (Sandbox Code Playgroud)\n\n现在,数据库中的架构已正确创建,但是,当我保留实体时Purchase,出现以下错误:
\n\n\nSQLSTATE[23000]:违反完整性约束:1048 列\n \'price_amount\' 不能为空
\n
我相信这一点:我还不明白这个机制是如何运作的。
\n\n如何设置和获取“真实”实体 ( Purchase) 的值?
我将值作为Money对象(我使用的值对象setPrice())传递给实体中的方法Purchase,但是,如何将该值拆分为两个属性amount和currency并在可嵌入类中设置?
因为执行var_dump(使用VarDumperdump()的功能)我以正确的方式获取实体集:
PurchaseListener.php on line 58:\nPurchase {#1795 \xe2\x96\xbc\n ...\n -price: Money {#1000 \xe2\x96\xbc\n -amount: 86\n -currency: Currency {#925 \xe2\x96\xbc\n -currencyCode: "EUR"\n }\n }\n}\nRun Code Online (Sandbox Code Playgroud)\n\n但这些值没有在 Embeddable 中设置,我不明白为什么......
\n\n我还尝试对嵌入类中的值进行硬编码,但无论如何它不起作用,而且我也不明白为什么:
\n\n/**\n * @ORM\\Embeddable\n */\nclass PriceEmbeddable\n{\n /** @ORM\\Column(type = "integer") */\n private $amount;\n\n /** @ORM\\Column(type = "string") */\n private $currency;\n\n public function __construct($value)\n {\n $this->currency = \'EUR\';\n $this->amount = 90;\n }\n\n public function setAmount($amount)\n {\n $this->amount = $amount = 90;\n }\n\n public function setCurrency($currency)\n {\n $this->currency = $currency = \'EUR\';\n }\n\n public function getAmount()\n {\n return $this->amount;\n }\n\n public function getCurrency()\n {\n return $this->currency;\n }\n}\nRun Code Online (Sandbox Code Playgroud)\n
这是简单的解决方案:
/**
* 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;
}
}
Run Code Online (Sandbox Code Playgroud)