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 机器人轨迹规划相关问题
  • ¥15 word样式右侧翻页键消失
  • ¥15 springboot+vue 集成keycloak sso到阿里云
  • ¥15 win7系统进入桌面过一秒后突然黑屏
  • ¥30 backtrader对于期货交易的现金和资产计算的问题
  • ¥15 求C# .net4.8小报表工具
  • ¥15 安装虚拟机时出现问题
  • ¥15 Selenium+docker Chrome不能运行
  • ¥15 mac电脑,安装charles后无法正常抓包
  • ¥18 visio打开文件一直显示文件未找到