2012-11-09 38 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