2012-11-09 37 views
0

我想合并这2个请求在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
+0

你想要的到底是什么?这2个查询返回不同的信息,你想如何合并它们? – j0k

+0

这两个查询使用相同的表,第一个使用第二个,所以我认为这可能会更好地做到这一点,以优化这一点。但也许我错了? – MaximeBernard

回答

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 1.2 Optimization

+0

哦,我明白了!所以你必须在Doctrine查询中注入纯粹的SQL?我认为它可能会更好地优化请求产品并同时计数。 – MaximeBernard

+1

另一种方法来做到这一点我不知道。这种方法在文档中描述,它的工作原理,我认为它比做两个请求更好:-) – denys281

+0

是不是你打开自己的SQL注入攻击时创建一个像这样的查询?查询应该被参数化。 – oalbrecht