【问题标题】:Symfony2 - Is there any way to create virtual field in entity?Symfony2 - 有没有办法在实体中创建虚拟字段?
【发布时间】:2017-04-17 07:19:11
【问题描述】:

请帮忙,我有一张表 orderstotal_priceexchange_code(它包含像美元这样的货币代码)、exchange_rate(包含像:1.7 这样的货币汇率)。

现在我想在这里创建一个虚拟字段“exchangedTotalPrice”,它将包含 exchangedTotalPrice = exchangeRate * totalPrice。

我不想在数据库中创建单独的列,因为我的 db 表中的列已经太多了,我的要求是创建更多的虚拟字段。

如果您需要任何内容​​或不理解我的查询,请发表评论。

【问题讨论】:

  • 为什么不直接实现方法public function getExchangedTotalPrice() { return $this->exchangeRate * $this->totalPrice; }
  • 感谢您的回复。那么我可以在查询生成器或查找功能中使用此功能吗?..

标签: doctrine-orm symfony-2.8


【解决方案1】:

您可以使用特定的方法来提供您需要的东西(如 cmets 中所述)。

public function getExchangedTotalPrice() 
{
     // do the maths and return the result.

     $result = $this->exchangeRate * $this->totalPrice; 

     return $result;
}

有趣的是,您可以在表单或许多其他地方挂钩。


表格

例如,如果您有一个表单,其构建器看起来像这样:

public function buildForm(FormBuilderInterface $builder, array $options)
{

     //... some other builder stuff here
     $builder->add('exchangedTotalPrice', TextType::class, [
         'mapped' => false,                // this will stop the setter being called on submit
     ]);
}

public function configureOptions(OptionsResolver $resolver)
{
    $resolver->setDefaults([
        'allow_extra_fields' => true,     // youll need this to allow the extra field element
    ]);
}

当 symfony 尝试填充表单时,它会尝试根据字段名称调用 getter 和 setter。因此将反过来使用您上面定义的方法。


树枝

twig 中也会出现同样的情况..

{{ Orders.exchangedTotalPrice }}

这也会调用新字段的getter。

我没有测试过这些,所以你可能需要调试。

【讨论】:

  • 感谢您的支持。这对我的情况很有帮助。 :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-04-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多