【问题标题】:How to get DQL result from the template with symfony 1.4?如何使用 symfony 1.4 从模板中获取 DQL 结果?
【发布时间】:2013-05-26 05:59:39
【问题描述】:

我正在使用 symfony 1.4 和 Doctrine。我正在写一个关于一些酒吧/酒吧的应用程序,我有 4 张桌子:

  • 产品
  • 订单
  • product_order
  • 酒吧。

我想获取所有产品在第一个 pub 中的订购时间(即 pubs.id = 1)。这就是我所拥有的,但我只能得到第一个产品的总和(products.id = 1),我需要所有产品的总和,在这种情况下,我的数据库中有两种不同的产品。

产品订单表:

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>";


      }

请帮助:)

【问题讨论】:

  • 很抱歉,但是...您能更好地解释一下您遇到的问题吗?
  • 我想得到每个产品的总和(l.amount)。我认为查询正在运行,但我不知道如何通过“$resultCount->getUnits()”

标签: php doctrine symfony-1.4


【解决方案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');

【讨论】:

  • 感谢您的回答 Michal,我找到了一个尝试 SQL 的函数,但它不是问题,它运行良好,我尝试了您的建议,但它只打印一条记录,如果我尝试,它必须打印 2手动访问第二条记录 (resultCount[1]['units']) 它说未定义的偏移量 1。更多建议请我生气:(
  • 您是否对数据库运行了查询并确定它应该返回两行?您有两个与id_pub = 1 关联的不同产品?
  • 100% 确定,phpmyadmin 返回 2 行。
  • 保持冷静,深呼吸——我们最终会找到原因的;)你能告诉我们Doctrine产生的SQL吗?
  • 嗯...奇怪。我添加了查询生成器的一些修改版本。你可以检查它是否改变了任何东西(理论上它不应该,但谁知道......)。您能否也发布此语句产生的内容(在ordersGetCount() 函数内:var_dump($q-&gt;getSqlQuery());
【解决方案2】:

你必须尝试删除

->groupBy('l.id_product')

它将您的结果减少到一种产品。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-05
    • 1970-01-01
    • 1970-01-01
    • 2012-08-23
    • 2012-08-06
    相关资源
    最近更新 更多