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 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)
  • ¥15 AIC3204的示例代码有吗,想用AIC3204测量血氧,找不到相关的代码。