我有一个像这样的InvoiceItem实体:
/**
* @Entity
*/
class InvoiceItem
{
[..]
/**
* @ManyToOne(targetEntity="Invoice", inversedBy="items")
* @JoinColumn(name="invoice_id", referencedColumnName="id")
* @var Invoice
*/
private $invoice;
/**
* @Column(type="decimal", scale="10", precision="3")
* @var float
*/
private $qty;
/**
* @Column(name="unit_price", type="decimal", scale="10", precision="3")
* @var float
*/
private $unitPrice;
[..]
}
我想返回一个数组,其中键将是发票的ID,值是qty * unitPrice的总和。
我可以使用这样的DQL查询返回总和:
SELECT SUM(I.qty * I.unitPrice) AS amount FROM Entities\\InvoiceItem I
WHERE I.invoice IN (..) GROUP BY I.invoice
结果:
array(
0 => array('amount' => '46.7'),
1 => array('amount' => '32.5')
)
但我不知道如何退回发票外键。我试过了
SELECT SUM(I.qty * I.unitPrice) AS amount, I.invoice
FROM Entities\\InvoiceItem I
WHERE I.invoice IN (..) GROUP BY I.invoice
但它不起作用(错误:无效的PathExpression。必须是StateFieldPathExpression。)
如何退回发票ID?我想使用ID作为结果数组的键:
array(
1005 => '46.7',
1250 => '32.5'
)
其中1005和1250是发票的ID。
更新2011-06-15
原生查询有效:
$rsm = new \Doctrine\ORM\Query\ResultSetMapping();
$rsm->addScalarResult('invoice_id', 'invoiceId');
$rsm->addScalarResult('amount', 'amount');
$q = $this->getEntityManager()->createNativeQuery(
'SELECT invoice_id, SUM(qty * unit_price) AS amount FROM invoices_items'
.' WHERE invoice_id IN ('.implode(',', $ids).') GROUP BY invoice_id',
$rsm
);
$result = $q->getResult();
结果:
array(
0 =>
array(
'invoiceId' => '1005',
'amount' => '46.7'
)
1 =>
array(
'invoiceId' => '1250',
'amount' => '32.5'
)
)
但我需要根据发票ID制作循环索引。
答案 0 :(得分:9)
您可以使用setHint()方法使外键与实体的其余值一起返回。您将该方法应用于查询(而不是查询构建器):
$q = $qb->getQuery();
$q->setHint(\Doctrine\ORM\Query::HINT_INCLUDE_META_COLUMNS, true);