2013-05-30 39 views
5

我正在使用symfony 1.4和Doctrine。我寫的一些酒吧/條的應用程序,我有4個表:如何從symfony 1.4的模板中獲得DQL結果?

  • 產品
  • 訂單
  • product_order
  • 酒吧。

我想要獲得所有產品在第一個酒吧(即pubs.id = 1)中訂購的時間。這是我得到的,但我只能得到第一個產品(products.id = 1)的總和,我需要它們的總和,在這種情況下,我的db中有兩種不同的產品。

ProductOrderTable:

public function ordersGetCount(){ 

    $q = Doctrine_Query::create() 

     ->from('ProductOrder l') 
     ->innerJoin('l.Order p ON l.id_order = p.id') 
     ->select('SUM(l.amount) as units') 
     ->andWhere('p.id_pub = 1') 
     ->groupBy('l.id_product') 
     ->orderBy('p.id'); 
    return $q->execute(); 
} 

這裏我的動作類:

$this->resultCount= Doctrine_Core::getTable('productorder')->ordersGetCount(); 

在這裏,我的模板:

for($i=0; $i<2; $i++){ 

      echo "<tr>"; 

      echo "<td>".$resultCount[0]->getUnits()[$i]."</td>";// 
      echo "<td>1</td>"; 
      echo "<td>1</td>"; 
      echo "</tr>"; 


     } 

請需要幫助:)

+0

抱歉,但......你能解釋一下你的問題嗎? – ilSavo

+0

我想獲得每個產品的總和(l.amount)。查詢工作我認爲,但我不知道如何通過「$ resultCount-> getUnits()」 – user2294971

回答

1

我認爲你的查詢沒有問題,但你應該看看你如何顯示你的結果。

echo "<td>".$resultCount[0]->getUnits()[$i]."</td>"; 

首先,你總是指$resultCount數組中的第一個元素。其次,我不知道,如果你可以使用一個getter的虛擬列(你不使用它映射到模型列

所以我會像這樣的東西去:

  1. ordersGetCount我會用

    return $q->fetchArray(); 
    

    這將返回一個數組的數組,而不是對象的數組,並允許您訪問虛擬列units

  2. 顯示結果:

    <?php foreach ($resultCount as $row): ?> 
        <tr> 
         <td> 
          <?php echo $row['units']; ?> 
         </td> 
         <td>1</td> 
         <td>1</td> 
        </tr> 
    <?php endforeach ?> 
    

編輯:

這是很奇怪的,)你可以嘗試建立查詢是這樣的:(理論上它應該是相同的):

$q = $this->createQuery('l') 
    ->select('l.id_product, sum(l.amount) as units') 
    ->innerJoin('l.Order') 
    ->where('p.id_pub = 1') 
    ->groupBy('l.id_product') 
    ->orderBy('p.id'); 
+0

感謝您的答案米哈爾,我發現一個函數來嘗試SQL,而不是它的工作原理好,我試過你的建議,但它只打印一個記錄它必須打印2,如果我嘗試手動訪問第二個記錄(resultCount [1] ['units'] )它說Undeffined偏移1. 更多的建議,請進我的生氣:( – user2294971

+1

您是否對數據庫運行查詢,並確保它應該返回兩行?您有兩個不同的產品與'id_pub = 1'關聯? –

+0

100%肯定,phpmyadmin返回2行。 – user2294971

0

你必須嘗試刪除

->groupBy('l.id_product') 

它將您的結果降至一種產品。

+0

感謝您的答案,我想獲得所有的產品:) – user2294971

相關問題