Doctrine:在1中合并2个请求

时间:2012-11-09 18:01:53

标签: php symfony1 doctrine symfony-1.4 doctrine-1.2

我想在1中合并这两个请求,但我不知道如何做到这一点。有什么想法吗?

$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();
  • 学说:1.2
  • Symfony:1.4
  • PHP:5.3

1 个答案:

答案 0 :(得分:1)

您可以使用子查询,因为您的查询不相同。这里以DQL: Doctrine Query Language为例。这里是伪代码,我不知道它是否会立即起作用。

$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

您在$result中获得了一个数组。执行var_dump()并检查其内容。我不确定这段代码会立刻起作用,但我建议你朝着这个方向前进。

p.s:我建议你这个有关Doctrine查询优化的有趣演示文稿:Doctrine 1.2 Optimization