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;
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
(ex: if i write 5 in label $a et 5 in label $b - i need to have 10 write directly in the label $calcul....)
I do not recommend to do such a thing as persisting calculated data to a database ( 3FN Explanation ).
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.
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
// 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();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.