dongpiansui8755 2013-10-21 10:00
浏览 61
已采纳

Symfony2 Doctrine使用生成的from和entity计数

I needed to count the quantity of rows in a table of Workers (similar to the classic person) entity:

class Worker
{
/**
 * @ORM\Id
 * @ORM\Column(type="integer")
 * @ORM\GeneratedValue(strategy="AUTO")
 */
private $idWorker;

/**
 * @ORM\Column(type="string", length=20)
 */
private $omang;

/**
 * @ORM\Column(type="string", length=100)
 */
private $workerTitle;


/**
 * @ORM\Column(type="string", length=100)
 */
private $workerName;

......these other variables are also in the entity, but they are generated with the day of bith of the worker:

//date of retirement
private $retireYear;
//time to retirement
private $timeToRetirement;

//Time left in: Years, Months and days these are INTEGER VALUES
private $yearsLeft;
private $monthsLetf;
private $daysLeft;

In the Worker repository I have this function that works to count all rows:

   public function countTotalWorkers (){
     $query = $this->createQueryBuilder('Worker')->select('COUNT(Worker)');
     $total = $query->getQuery()->getSingleScalarResult();
     return $total;
   }

Now I want to do something different, I want to count all the Rows that for instance have yearsLeft smaller than 1, but years left is not in the database, as I said it is a generated value that lives inside Worker, and it's generated in a public function of the class... Feel free to ask if you think you need more information... thank you in advanced.

  • 写回答

1条回答 默认 最新

  • dongwanqiang_2017 2013-10-22 18:01
    关注

    In order to do that you have two ways:

    Select all workers from database

    Doing this, you are able to load the worker data that generates the yearleft value. Then, you could do something like this:

    $workers = $this->getRepository('Worker')->findAll();
    
    $total = 0;
    foreach ($workers as $w)
    {
        if ($w->getYearsLeft() < 1)
            $total ++;
    }
    

    Store the yearsLeft in db

    I do not what could be the best implementation for your scenario, but if eventually you store this value at db, you could do:

    $query = $this->createQueryBuilder();
    $query->select('count(w.id)');
    $query->from('Worker', 'w');
    $query->where('w.yearsLeft < ?1');
    $query->setParameter(1, 1);
    
    $total = $query->getQuery()->getSingleScalarResult;
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?
  • ¥15 matlab(相关搜索:紧聚焦)
  • ¥15 基于51单片机的厨房煤气泄露检测报警系统设计
  • ¥15 Arduino无法同时连接多个hx711模块,如何解决?