繁体   English   中英

使用实体 SYMFONY 中的构造函数进行计算

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM