我有兩個實體,發票和InvoiceItem在yml中定義如下。奇怪的學說實體行爲
Invoice.orm.yml
AppBundle\Entity\Invoice:
type: entity
table: invoices
repositoryClass: AppBundle\Repository\InvoiceRepository
fields:
id:
id: true
type: integer
generator:
strategy: AUTO
......
oneToMany:
items:
targetEntity: InvoiceItem
mappedBy: invoice
deductions:
targetEntity: InvoiceDeduction
mappedBy: invoice
payments:
targetEntity: InvoicePayment
mappedBy: invoice
InvoiceItem.orm.yml
AppBundle\Entity\InvoiceItem:
type: entity
table: invoice_items
repositoryClass: AppBundle\Repository\InvoiceItemRepository
fields:
id:
id: true
type: integer
generator:
strategy: AUTO
....
manyToOne:
invoice:
targetEntity: Invoice
inversedBy: items
joinColumn:
invoice_id:
referencedColumnName: id
onDelete: CASCADE
我的控制器接收發票細節並保存元件如下圖所示
public function createInvoiceAction(Request $request)
{
....
$invoice = new Invoice();
$invoice->setReference($ref);
$invoice->setInvoiceDate(\DateTime::createFromFormat('d/m/Y',$request->query->get('invoiceDate')));
$invoice->setDescription($request->query->get('summary'));
$invoice->setAttn($request->query->get('att'));
$invoice->setIsVatable($request->query->get('vattable') == 'true' ? 1 : 0);
$invoice->setAdditionalInstructions($request->query->get('additional'));
$invoice->setJob($job);
$invoice->setCurrency($request->query->get('currency'));
$invoice->setGeneratedBy($createdBy);
$invoice->setFile($filename);
$job->setStatus('Invoiced');
$em->persist($invoice);
$em->persist($job);
$em->flush();
$items = $request->query->get('items');
for($i=0;$i<count($items);$i++)
{
if($items[$i]['description']!= '' && $items[$i]['amount'] != '')
{
$item = new InvoiceItem();
$item->setDescription($items[$i]['description']);
$item->setAmount($items[$i]['amount']);
$item->setInvoice($invoice);
$em->persist($item);
$em->flush();
}
}
$deductions = $request->query->get('deductions');
for($i=0;$i<count($deductions);$i++)
{
if($deductions[$i]['description'] != '' && $deductions[$i]['value'] != '')
{
$deduction = new InvoiceDeduction();
$deduction->setDescription($deductions[$i]['description']);
$deduction->setValue($deductions[$i]['value']);
$deduction->setIsPercentage($deductions[$i]['isPercentage'] == 'true' ? 1 : 0);
$deduction->setInvoice($invoice);
$em->persist($deduction);
$em->flush();
}
}
$html = $this->renderView('AppBundle:Default:invoice.html.twig', array('invoice' => $invoice));
return new Response(
$html
);
}
invoice.html .twig呈現發票詳細信息,包括項目和扣減項目。
.....
{% for item in invoice.items %}
<tr>
<td>{{ loop.index }}</td>
<td>{{ item.description }}</td>
<td>{{ item.amount|number_format(0, '', ',') }}</td>
</tr>
{% endfor %}
.....
我遇到的挑戰是發送到模板的$ invoice對象沒有任何項目或扣減應該是集合。我檢查了數據庫,可以確認這些項目和扣減項目是否保留在相應的表格中,因此我不明白爲什麼表格中沒有invoice.items或invoice.deductions。
絕望之餘,我在每個InvoiceItem對象創建思想後都刷新了,可能在持久化事務完成之前呈現模板,但這也沒有幫助。
仔細檢查發票項目數據庫表。我懷疑invoice_id是NULL? – Cerad