Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get DQL result from the template with symfony 1.4?

I'm working with symfony 1.4 and Doctrine. I'm writing an app about some pubs/bars, and I've got 4 tables:

  • products
  • orders
  • product_order
  • pubs.

I want to get the times all products have been ordered in the first pub (i.e. pubs.id = 1). This is what I've got, but I can only get the sum of the first product (products.id = 1) and I need the sum of all of them, in this case there are two different products in my 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();
}

Here my action class:

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

And here my template:

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


      }

Please need help :)

like image 996
user2294971 Avatar asked Nov 13 '22 04:11

user2294971


1 Answers

I think there's nothing wrong with your query, but you should have a look at how you display your results.

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

Firstly, you're always referring to the first element in the $resultCount array. Secondly, I'm not sure if you can use a getter for a virtual column (you're not using a column which is mapped to your model.

So I would go with something like this:

  1. In the ordersGetCount I would use

    return $q->fetchArray();
    

    This will return an array of arrays, not an array of objects, and will allow you to access the virtual column units.

  2. To display the results:

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

EDIT:

This is quite strange ;) Can you try to build the query this way: (in theory it should be the same):

 $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');
like image 154
Michal Trojanowski Avatar answered Nov 14 '22 23:11

Michal Trojanowski