Symfony2 - 有没有办法在实体中创建虚拟字段?

Symfony2 - Is there any way to create virtual field in entity?

请帮忙,我有一个 table orders total_priceexchange_code(它包含像美元这样的货币代码),exchange_rate(包含货币比率:1.7).

现在我想创建一个虚拟字段 'exchangedTotalPrice',其中将包含 exchangedTotalPrice = exchangeRate * totalPrice。

我不想在数据库中创建一个单独的列,因为我的数据库中已经有太多列 table 并且我的要求是创建更多的虚拟字段。

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

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

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。因此将依次使用您上面定义的方法。


树枝

树枝中也会出现同样的情况..

{{ Orders.exchangedTotalPrice }}

这也会在新字段上调用 ​​getter。

Ive not tested any of this, so you might need to debug.