我正在使用symfony 2.3。我試圖爲每個月底的每個商業廣告生成發票。我實現了一個名爲InvoiceListener的監聽程序。問題是updateInvoice()函數不會將數據插入到發票表中。系統不會呈現錯誤。正確顯示查詢的原則debuger。
InvoiceListener.phpsymfony2:使用eventListener插入數據
class InvoiceListener {
private $em;
public function __construct(\Doctrine\ORM\EntityManager $em) {
$this->em = $em;
}
public function process(GetResponseEvent $event) {
$expire = '2012-01-01';
$current_month = date("m");
$current_year = date("y");
if (date("d") == 1) {
echo 'first day';
$this->updateStatus($current_month, $current_year);
$this->updateInvoice();
} else {
echo 'not first day';
$users = $this->findByRole('ROLE_COMMERCIAL');
// update invoice
$this->updateInvoice($users);
}
}
public function updateStatus($current_month, $current_year) {
$queryBuilder = $this->em->createQueryBuilder();
$queryBuilder
->update('Biginfo\UserBundle\Entity\User', 'u')
->set('u.nbrBusiness', 1)
->set('u.month', $current_month)
->set('u.year', $current_year);
return $queryBuilder->getQuery()->getResult();
}
public function updateInvoice($users) {
$queryBuilder = $this->em->createQueryBuilder();
foreach ($users as $user) {
$queryBuilder
->update('Biginfo\AdminBundle\Entity\Invoice', 'c')
->set('c.commercial', $user->getId())
->set('c.month', $user->getMonth())
->set('c.year', $user->getYear())
->set('c.nbrBusiness', $user->getNbrBusiness());
}
return $queryBuilder->getQuery()->getResult();
}
/**
* @param string $role
*
* @return array
*/
public function findByRole($role) {
$qb = $this->em->createQueryBuilder();
$qb->select('u')
->from('Biginfo\UserBundle\Entity\User', 'u')
->where('u.roles LIKE :roles')
->setParameter('roles', '%"' . $role . '"%');
return $qb->getQuery()->getResult();
}
}
「_...我試圖爲每個廣告的每一個月末產生一張發票......_」 - 聽起來像你需要[控制檯命令](http://symfony.com /doc/current/cookbook/console/console_command.html),並用cronjob調用它。 – BentCoder
我同意@BentCoder。爲此使用一個監聽器是一種矯枉過正的行爲。 – tftd
也同意@BentCoder,應該使用控制檯 – MouradK