我正在尝试在 Symfony 2 项目中使用 Doctrine 嵌入式。
我有一个类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"
}
}
}
但是这些值没有在 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;
}
}
最佳答案
这是简单的解决方案:
/**
* 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;
}
}
关于doctrine-orm - 如何使用 Doctrine Embeddables,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32274233/