[英]CALCUL WITH CONSTRUCTOR IN ENTITY SYMFONY
i need to do a calcul in an entity with symfony (sonata) like: i have 3 labels in my entity with doctrine and i need to save in database a result of: $calcul = $ a + $b;我需要在具有symfony (奏鸣曲)的实体中进行计算,例如:我的实体中有 3 个带有 doctrine 的标签,我需要将结果保存在数据库中: $calcul = $ a + $b;
here is my entity这是我的实体
class National
{
/**
* @var int
*/
private $id;
/**
* @var string(unique=true)
*/
private $selection;
/**
* @var int
*/
private $a;
/**
* @var int
*/
private $b;
/**
* @var string
*/
private $total;
and this is my classic setter and getter这是我的经典二传手
/**
* Set a
*
* @param string $a
*
* @return Events
*/
public function setA($a)
{
$this->a = $a;
return $this;
}
/**
* Get a
*
* @return string
*/
public function getA()
{
return $this->a;
}
/**
* Set b
*
* @param string $b
* @return Events
*/
public function setB($b)
{
$this->b = $b;
return $this;
}
so the question is how to do the constructor ???所以问题是如何做构造函数???
to have the result in $calcul save in the database将 $calcul 中的结果保存在数据库中
(ex: if i write 5 in label $a et 5 in label $b - i need to have 10 write directly in the label $calcul....) (例如:如果我在 label $a 中写入 5,在 label $b 中写入 5 - 我需要直接在 label $calcul 中写入 10...)
I do not recommend to do such a thing as persisting calculated data to a database ( 3FN Explanation ).我不建议将计算数据保存到数据库中( 3FN 解释)。
In a general way you don't want to store a fields which is a result from two or more other fields, as if you need to update one of the original fields, this will also require you to re-calculated a re-store the result at each time, requiring a few more operations each time.一般来说,您不想存储一个来自两个或多个其他字段的字段,就好像您需要更新其中一个原始字段一样,这也需要您重新计算重新存储每次结果,每次都需要更多操作。
Also, if fore some reason the calcul must change, you'll have to update all of the data which was done with a former calcul.此外,如果由于某种原因计算必须更改,您将必须更新使用以前的计算完成的所有数据。 This will become very hard to manage.
这将变得非常难以管理。
If you need to retrieve the results of two or more fields, this should be perform by calling a function where you need it.如果您需要检索两个或更多字段的结果,应在需要的地方调用 function 来执行此操作。
Of course, if you still want to do that, or really need it, the way to do it would be:当然,如果您仍然想这样做,或者确实需要它,那么这样做的方法是:
class National {
... // Your fields, getters and setters
public function calculTotal() {
$this->total = $this->a + $this->b;
return $this;
}
}
In your controller or service在您的 controller 或服务中
// Fetch you National entity from repository
// Perform the calcul
$national->calculTotal()
// Persist the national entity with the new 'total' fields added to it
$this->entityManager->perist($national);
$this->entityManager->flush();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.