[英]CALCUL WITH CONSTRUCTOR IN ENTITY SYMFONY
我需要在具有symfony (奏鳴曲)的實體中進行計算,例如:我的實體中有 3 個帶有 doctrine 的標簽,我需要將結果保存在數據庫中: $calcul = $ a + $b;
這是我的實體
class National
{
/**
* @var int
*/
private $id;
/**
* @var string(unique=true)
*/
private $selection;
/**
* @var int
*/
private $a;
/**
* @var int
*/
private $b;
/**
* @var string
*/
private $total;
這是我的經典二傳手
/**
* 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;
}
所以問題是如何做構造函數???
將 $calcul 中的結果保存在數據庫中
(例如:如果我在 label $a 中寫入 5,在 label $b 中寫入 5 - 我需要直接在 label $calcul 中寫入 10...)
我不建議將計算數據保存到數據庫中( 3FN 解釋)。
一般來說,您不想存儲一個來自兩個或多個其他字段的字段,就好像您需要更新其中一個原始字段一樣,這也需要您重新計算重新存儲每次結果,每次都需要更多操作。
此外,如果由於某種原因計算必須更改,您將必須更新使用以前的計算完成的所有數據。 這將變得非常難以管理。
如果您需要檢索兩個或更多字段的結果,應在需要的地方調用 function 來執行此操作。
當然,如果您仍然想這樣做,或者確實需要它,那么這樣做的方法是:
class National {
... // Your fields, getters and setters
public function calculTotal() {
$this->total = $this->a + $this->b;
return $this;
}
}
在您的 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.