使用默认值

时间:2015-06-19 11:03:18

标签: php symfony doctrine

我有一个带有值的字段的实体(可以为null)。在另一个表中,我有默认值。我想覆盖实体的值(使用默认表中的值),如果它是null。

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有什么东西能让我这么做吗?

也许是约束?

3 个答案:

答案 0 :(得分:1)

约束不是一种选择。也许你可以通过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);
        }
    }
}

我没有尝试过,我根本没有尝试过这个,但我认为它可以帮助你了解一下......

答案 1 :(得分:1)

您可以在Products和Defaults之间定义一对一的关系,然后使用此getter:

function getPrice()
{
    if (null === $this->price) 
    {
        return $this->default->getPrice();
    }

    return $this->price; 
}
PD:我不能评论xurshid29的帖子,但这可能不会起作用,因为他需要从表中检索值,注入任何存储库都会抛出循环引用异常(他可以注入容器)

答案 2 :(得分:0)

要在检索时覆盖值,请扩展Doctrine EntityRepository,以便覆盖和/或创建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());
        }
    }
}