-2

我想添加for循环以在php中填充变量中的数据。所以我得到查询结果的行。如何应用循环并在dql中获取查询结果的行数?

这是我的代码:

public function invoicepreviewAction(){
    if(isset($_SESSION['invoiceid'])) {
        $invoiceid=$_SESSION['invoiceid'];
    }
    if(isset($_SESSION['date'])) {
        $dateofinvoice=$_SESSION['date'];
    }
    $em = $this->getDoctrine()->getManager();
    $query = $em->createQuery("select a.companyName,a.companyAddress,a.companyPobox,a.companyCity,a.companyCountry,c.firstName,c.lastName,c.address,c.city,c.country,c.phoneNumber,i.notes from InvoicesInvoicesBundle:Invoices i,ClientsClientsBundle:Clients c,AccountsAccountsBundle:Accounts a where i.id='".$invoiceid."' and i.accountID=a.id and i.clientID=c.id");
    $invoices = $query->getResult();
    $companyname=$invoices[0]['companyName'];
    $comanyaddress=$invoices[0]['companyAddress'];
    $companypobox=$invoices[0]['companyPobox'];
    $companycity=$invoices[0]['companyCity'];
    $companycountry=$invoices[0]['companyCountry'];
    $firstname=$invoices[0]['firstName'];
    $lastname=$invoices[0]['lastName'];
    $address=$invoices[0]['address'];
    $city=$invoices[0]['city'];
    $country=$invoices[0]['country'];
    $notes=$invoices[0]['notes'];
    $phonenumber=$invoices[0]['phoneNumber'];
    $date=$dateofinvoice;
    return $this->render('InvoicesInvoicesBundle:Invoices:invoicepreview.html.twig', array(
    'companyname' =>$companyname,
    'companyaddress' => $comanyaddress,
    'companypobox' => $companypobox,
    'companycity' => $companycity,
    'companycountry' =>$companycountry,
    'firstname' => $firstname,
    'lastname' => $lastname,
    'address' => $address,
    'city' => $city,
    'country' => $country,
    'notes' => $notes,
    'phonenumber' => $phonenumber,
    'date' => $date,            
    ));
}
4

1 回答 1

2

没有必要在控制器中大量拆分结果。同样,通过 $invoices[0] 您显然只是从第一个结果中获取数据。

只需将 invoices 变量传递到模板并在 twig 中循环遍历它。

//controller
...
return $this->render('InvoicesInvoicesBundle:Invoices:invoicepreview.html.twig', array(
    'invoices' => $invoices
));

{# twig template #}
{% for invoice in invoices %}
    {# render any data you want here with the required html #}
    {{ invoice.companyName }}
    {# ... #}
{% endfor %}
于 2013-10-04T10:20:47.870 回答