Magento 中获取 Zend_Db_Select对象中的SQL语句

piaoling  2011-08-10 13:57:58

magento是基于Zend Framework的,所以底用的还是zend的zend db

今天在分析Magento源代码的时候,在文件app/code/core/Mage/Catalog/model/Resource/Eav /Mysql4/Config.php 中追踪到下面的函数 getAttributesUsedInListing()

01 /**
02 * Retrieve Product Attributes Used in Catalog Product listing
03 *
04 * @return array
05 */
06 public function getAttributesUsedInListing() {
07 $select = $this->_getReadAdapter()->select()
08 ->from(array(’main_table’ => $this->getTable(’eav/attribute’)))
09 ->join(
10 array(’additional_table’ => $this->getTable(’catalog/eav_attribute’)),
11 ‘main_table.attribute_id = additional_table.attribute_id’,
12 array()
13 )
14 ->joinLeft(
15 array(’al’ => $this->getTable(’eav/attribute_label’)),
16 ‘al.attribute_id = main_table.attribute_id AND al.store_id = ‘ . (int) $this->getStoreId(),
17 array(’store_label’ => new Zend_Db_Expr(’IFNULL(al.value, main_table.frontend_label)’))
18 )
19 ->where(’main_table.entity_type_id=?’, $this->getEntityTypeId())
20 ->where(’additional_table.used_in_product_listing=?’, 1);
21 $sql = $select->assemble();
22 echo $sql;
23 return $this->_getReadAdapter()->fetchAll($select);
24 }

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

1 SELECT `main_table`.*,
2 IFNULL(al.value, main_table.frontend_label) AS `store_label`
3 FROM `eav_attribute` AS `main_table`
4 INNER JOIN `catalog_eav_attribute` AS `additional_table`
5 ON main_table.attribute_id = additional_table.attribute_id
6 LEFT JOIN `eav_attribute_label` AS `al`
7 ON al.attribute_id = main_table.attribute_id AND al.store_id = 1
8 WHERE (main_table.entity_type_id=’4′)
9 AND (additional_table.used_in_product_listing=1)
Magento 中获取 Zend_Db_Select对象中的SQL语句

文章作者:POPO4J
本文地址:http://www.popo4j.com/article/Magento-get-Zend_Db_Select-SQL-statement.html
版权所有 © 转载时必须以链接形式注明作者和原始出处!

类别 :  magento(258)  |  浏览(3990)  |  评论(0)
发表评论(评论将通过邮件发给作者):

Email: