Magento中获取Zend DB对象中的SQL语句

Magento操作数据库是在 Zend DB(Zend Framework)的基础上简单的做了下封装了。Zend DB 有自己的一套规则,来组合生成最终的SQL查询语句,可以看到上面的代码中有 from() join() joinLeft() where() 等函数,乱七八糟的一大堆东西,需要对 Zend DB的规则非常熟悉,才能知道实际执行的SQL语句,有没有办法直接打印出SQL语句?找了下,还真有,就是assemble()函数。在上面代码中最后部分可以看到。


assemble()函数得到的SQL:

      SELECT `main_table`.*,     
      IFNULL(al.value, main_table.frontend_label) AS `store_label`   
      FROM `eav_attribute` AS `main_table`   
      INNER JOIN `catalog_eav_attribute` AS `additional_table`   
      ON main_table.attribute_id = additional_table.attribute_id     
      LEFT JOIN `eav_attribute_label` AS `al`   
      ON al.attribute_id = main_table.attribute_id AND al.store_id = 1   
      WHERE (main_table.entity_type_id='4')     
      AND (additional_table.used_in_product_listing=1)  
    

在文件app/code/core/Mage/Catalog/model/Resource/Eav /Mysql4/Config.php 中追踪到下面的函数 getAttributesUsedInListing()

      /**  
      * Retrieve Product Attributes Used in Catalog Product listing    
      *  
      * @return array  
      */  
      public function getAttributesUsedInListing() {     
      $select = $this->_getReadAdapter()->select()     
      ->from(array(’main_table’ => $this->getTable(’eav/attribute’)))     
      ->join(   
      array(’additional_table’ => $this->getTable(’catalog/eav_attribute’)),     
      ‘main_table.attribute_id = additional_table.attribute_id’,     
      array()   
      )   
      ->joinLeft(   
      array(’al’ => $this->getTable(’eav/attribute_label’)),     
      ‘al.attribute_id = main_table.attribute_id AND al.store_id = ‘ . (int) $this->getStoreId(),   
      array(’store_label’ => new Zend_Db_Expr(’IFNULL(al.value, main_table.frontend_label)’))     
      )   
      ->where(’main_table.entity_type_id=?’, $this->getEntityTypeId())   
      ->where(’additional_table.used_in_product_listing=?’, 1);     
      – $sql = $select->assemble();   
      – echo $sql;   
      return $this->_getReadAdapter()->fetchAll($select);   
      }  
    

相关文章:

1、Magento用SQL语句开发篇
https://www.onexin.net/posts-with-the-sql-statement-magento-development/

2、Magento常用SQL语句实用篇
https://www.onexin.net/practical-tips-commonly-used-sql-statement-magento/

3、教你看懂Magento中的SQL语句
https://www.onexin.net/magento-teach-you-to-understand-the-sql-statement/

4、Magento中如何调用SQL语句
https://www.onexin.net/how-to-call-sql-statements-magento/

5、创建 PDO 实例请求连接SQL数据库
https://www.onexin.net/pdo-database/

转载请注明出处:https://www.onexin.net/magento-zend-db-object-for-sql-statements/

Leave a Reply

Your email address will not be published. Required fields are marked *