0

我想将这 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
4

1 回答 1

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()并检查其内容。我不确定这段代码是否会立即生效,但我建议您朝着这个方向前进。

ps:我向您推荐这个关于 Doctrine 查询优化的有趣演示文稿:Doctrine 1.2 Optimization

于 2012-11-09T22:03:30.837 回答