使用默认值覆盖实体上的字段
Overwriting field on on entity with a default value
我有一个实体,它的字段有一个值(可以为空)。在另一个 table 中,我有默认值。如果它为空,我想覆盖实体的值(使用默认值 table 中的值)。
products
+- country_id -+- price -+
| 1 | 100 |
| 2 | NULL |
+--------------+---------+
defaults
+- country_id -+- price -+
| 1 | 10 |
| 2 | 99 |
+-------------+----------+
// this product should load price from defaults
$product = $productRepository->findOneBy(['country_id' => 2]);
Symfony 是否允许我这样做?
也许有限制?
约束不是一种选择。也许你可以通过 Doctrine (documentation is here) 提供的 postLoad
事件来实现它,像这样:
public function postLoad(LifecycleEventArgs $args)
{
$entity = $args->getEntity();
if ($entity instanceof YOUR_ENTITY)
{
if (null == $entity->getMYFIELD())
{
$entity->setMYFIELD(NEW_VALUE);
}
}
}
我没试过,我根本没试过这个,但我认为它应该能帮助你得到一个想法..
要在检索时覆盖值,扩展 Doctrine EntityRepository
以便您可以覆盖 and/or 创建 custom method。例如:
use Doctrine\ORM\EntityRepository;
class ProductRepository extends EntityRepository
{
public function findOneByCountry($country_id)
{
$product = $this->findOneBy(['country_id' => $country_id]);
if ($product->getPrice() === null) {
$default = $this->getEntityManager()
->getRepository('AcmeBundle:Default')
->findOneBy(['country_id' => $country_id])
;
$product->setPrice($default->getPrice());
}
}
}
您可以定义 Products 和 Defaults 之间的一对一关系,然后 getter:
function getPrice()
{
if (null === $this->price)
{
return $this->default->getPrice();
}
return $this->price;
}
PD:我无法评论 xurshid29 的 post,但这可能行不通,因为他需要从 table 检索值,并且注入任何存储库都会引发循环引用异常(尽管他可以注入容器)。
我有一个实体,它的字段有一个值(可以为空)。在另一个 table 中,我有默认值。如果它为空,我想覆盖实体的值(使用默认值 table 中的值)。
products
+- country_id -+- price -+
| 1 | 100 |
| 2 | NULL |
+--------------+---------+
defaults
+- country_id -+- price -+
| 1 | 10 |
| 2 | 99 |
+-------------+----------+
// this product should load price from defaults
$product = $productRepository->findOneBy(['country_id' => 2]);
Symfony 是否允许我这样做?
也许有限制?
约束不是一种选择。也许你可以通过 Doctrine (documentation is here) 提供的 postLoad
事件来实现它,像这样:
public function postLoad(LifecycleEventArgs $args)
{
$entity = $args->getEntity();
if ($entity instanceof YOUR_ENTITY)
{
if (null == $entity->getMYFIELD())
{
$entity->setMYFIELD(NEW_VALUE);
}
}
}
我没试过,我根本没试过这个,但我认为它应该能帮助你得到一个想法..
要在检索时覆盖值,扩展 Doctrine EntityRepository
以便您可以覆盖 and/or 创建 custom method。例如:
use Doctrine\ORM\EntityRepository;
class ProductRepository extends EntityRepository
{
public function findOneByCountry($country_id)
{
$product = $this->findOneBy(['country_id' => $country_id]);
if ($product->getPrice() === null) {
$default = $this->getEntityManager()
->getRepository('AcmeBundle:Default')
->findOneBy(['country_id' => $country_id])
;
$product->setPrice($default->getPrice());
}
}
}
您可以定义 Products 和 Defaults 之间的一对一关系,然后 getter:
function getPrice()
{
if (null === $this->price)
{
return $this->default->getPrice();
}
return $this->price;
}
PD:我无法评论 xurshid29 的 post,但这可能行不通,因为他需要从 table 检索值,并且注入任何存储库都会引发循环引用异常(尽管他可以注入容器)。