2017-04-17 40 views
2

请帮助,我有一个表orderstotal_price,exchange_code(它包含货币代码如USD),exchange_rate(包含货币汇率像:1.7)。Symfony2 - 有没有什么办法在实体中创建虚拟字段?

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

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

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

+0

为什么不只是实现方法'public function getExchangedTotalPrice(){return $ this-> exchangeRate * $ this-> totalPrice; ''? –

+0

感谢您的回复。那么我可以在查询生成器或查找函数中使用这个函数吗?.. – Vikash

回答

1

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

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 }} 

这也将呼吁新的领域,吸气。

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

+0

感谢您的支持。这对我的情况非常有帮助。 :) – Vikash

+0

最受欢迎,祝你好运! – DevDonkey

相关问题