我正在使用symfony 2.3。我正试图为每个月的每个商业广告制作一张发票。我实现了一个名为 InvoiceListener 的监听器。问题是 updateInvoice()函数不会将数据插入发票表。系统不会渲染错误。正确显示查询的学说debuger InvoiceListener.php
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();
}
}
答案 0 :(得分:1)
除非我遗漏了某些内容,否则您的代码只会一遍又一遍地更新同一条记录,我认为这不是您想要的。要生成新发票,您应该像这样更改:
public function updateInvoice($users) {
$queryBuilder = $this->em->createQueryBuilder();
$queryBuilder->insert('Biginfo\AdminBundle\Entity\Invoice', 'c');
foreach ($users as $user) {
$queryBuilder->values(array(
'c.commercial' => $user->getId(),
'c.month' => $user->getMonth(),
'c.year'=> $user->getYear(),
'c.nbrBusiness' => $user->getNbrBusiness()
))
}
return $queryBuilder->getQuery()->getResult();
}
P.S。您还应该使用占位符,请参阅http://doctrine-dbal.readthedocs.org/en/latest/reference/query-builder.html#binding-parameters-to-placeholders
“插入”命令has been added in Doctrine 2.5.0 BETA 3,因此它可能在Symfony 2.3中不可用。另一种方法是使用纯SQL,例如
public function updateInvoice($users) {
$connection = $this->container->get('doctrine.dbal.default_connection');
$values = array();
foreach ($users as $user) {
$values[] = "(
'" . $user->getId() . "',
'" . $user->getMonth() . "',
'" . $user->getYear() . "',
'" . $user->getNbrBusiness() . "'
)";
}
$sql = "INSERT INTO invoice (`commercial`, `month`, `year`, `nbrBusiness`) VALUES " . implode("," , $values);
$statement = $connection->prepare($sql);
$statement->execute();
}