简体   繁体   中英

Symfony2 Doctrine counting using a generated from and 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.

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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