gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 09:02:47 24 4
gpt4 key购买 nike

请帮忙,我有一个表 orders,其中包含 total_priceexchange_code(其中包含货币代码,如 USD)、exchange_rate(包含货币汇率,例如:1.7)。

现在我想创建一个虚拟字段“exchangedTotalPrice”,其中包含 ExchangedTotalPrice = ExchangeRate * TotalPrice。

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

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

最佳答案

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

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

同样的情况也会发生在 Twig 上..

{{ Orders.exchangedTotalPrice }}

这还将调用新字段上的 getter。

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

关于doctrine-orm - Symfony2 - 有没有办法在实体中创建虚拟字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43447023/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com