2012-06-10 44 views
5

我在一些Web應用程序項目中使用Symfony的Doctrine。確定哪個字段導致Doctrine重新查詢數據庫

我已經優化了這些項目中的許多查詢,以便只從數據庫中選擇所需的字段。但隨着時間的推移,新功能已被添加,並且 - 在一些情況下 - 代碼中會使用額外的字段,導致Doctrine懶惰加載程序重新查詢數據庫,並將某些頁面上的查詢數量從3增加到100+以上

所以我需要更新原始查詢以包含所有必填字段。然而,對於Doctrine而言,似乎沒有一種簡單的方法來記錄哪個字段導致發出附加查詢 - 因此,篩選代碼以查找不在原始查詢中的字段的用法成爲一項艱鉅的工作。

當getter訪問一個未被水合過的字段時,有沒有辦法讓Doctrine記錄日誌?

回答

1

我還沒有這個問題,只是看了Doctrine_Record類。你有沒有嘗試在_get()方法中添加一些調試輸出?我認爲這部分是你應該尋找一個解決方案:

if (array_key_exists($fieldName, $this->_data)) { 
     // check if the value is the Doctrine_Null object located in self::$_null) 
     if ($this->_data[$fieldName] === self::$_null && $load) { 
      $this->load(); 
     } 
+0

這是我最後走的路線。 –

1

只要打開SQL日誌,你可以推斷出別名有罪的。關於如何在Doctrine 1.2中做到這一點,請參見post

基本上:創建延伸Doctrine_EventListener類:

class QueryDebuggerListener extends Doctrine_EventListener 
{ 
    protected $queries; 

    public function preStmtExecute(Doctrine_Event $event) 
    { 
     $query = $event->getQuery(); 
     $params = $event->getParams(); 

     //the below makes some naive assumptions about the queries being logged 
     while (sizeof($params) > 0) { 
      $param = array_shift($params); 

      if (!is_numeric($param)) { 
       $param = sprintf("'%s'", $param); 
      } 

      $query = substr_replace($query, $param, strpos($query, '?'), 1); 
     } 

     $this->queries[] = $query; 
    } 

    public function getQueries() 
    { 
     return $this->queries; 
    } 
} 

並添加事件偵聽器:

$c = Doctrine_Manager::connection($conn); 
$queryDbg = new QueryDebuggerListener(); 
$c->addListener($queryDbg); 
+0

這是爲Doctrine2。 OP使用Doctrine 1。 – j0k

相關問題