Question

I would like to merge these 2 requests in 1 but I have no clue on how to do this. Any idea ?

$productsCount = Doctrine::getTable('Product')
            ->createQuery('p')
            ->where('p.store_id = ?', $store_id)
            ->andWhere('p.collection = ?', $this->product->getCollection())
            ->andWhere('p.image_path IS NOT NULL')
            ->count();

$productsCollection = Doctrine::getTable('Product')
            ->createQuery('p')
            ->where('p.store_id = ?', $store_id)
            ->andWhere('p.collection = ?', $this->product->getCollection())
            ->andWhere('p.status_id = ?', Product::_ONLINE)
            ->andWhere('p.id<>?', $this->product_id)
            ->offset(rand(0, $productsCount - 1))
            ->execute();
  • Doctrine: 1.2
  • Symfony: 1.4
  • PHP: 5.3
Was it helpful?

Solution

You can use subquery, because your query is not identical. Here DQL: Doctrine Query Language some example. And here is pseudocode, I do not know if it will work at once.

$q = Doctrine_Query::create()
            ->from('Product p')
            ->select('id, sum(id) as sumEntries') 
            ->addSelect('(SELECT id, name) // and else fields that you need
                        FROM Product a
                        WHERE (
                        a.store_id  = '.$store_id.' 
                        AND  
                        a.collection = '.$this->product->getCollection().'
                        AND
                        a.id<>= '.$this->product_id.' 
                        )
                        OFFSET '.rand(0, $productsCount - 1).') // I am not sure in this line
                        as resultSubquery')

            ->where('p.store_id = ?', $store_id)
            ->andWhere('p.collection = ?', $this->product->getCollection())
            ->andWhere('p.image_path IS NOT NULL')


  $result =  $q->execute(array(), Doctrine_Core::HYDRATE_ARRAY); //This greatly speeds up query

You get an array in $result. Do var_dump() and check its contents. I'm not sure that this code will work at once, but I advise you to move in this direction.

p.s: I recommend you this interesting presentation about Doctrine query optimization: Doctrine 1.2 Optimization

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top