2013-05-30 44 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

相关问题