magento是基于Zend Framework的,所以底层用的还是zend的zend db
今天在分析Magento源代码的时候,在文件app/code/core/Mage/Catalog/model/Resource/Eav /Mysql4/Config.php 中追踪到下面的函数 getAttributesUsedInListing()
06 |
public function getAttributesUsedInListing() { |
07 |
$select = $this ->_getReadAdapter()->select() |
08 |
->from( array (’main_table’ => $this ->getTable(’eav/attribute’))) |
10 |
array (’additional_table’ => $this ->getTable(’catalog/eav_attribute’)), |
11 |
‘main_table.attribute_id = additional_table.attribute_id’, |
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)’)) |
19 |
->where(’main_table.entity_type_id=?’, $this ->getEntityTypeId()) |
20 |
->where(’additional_table.used_in_product_listing=?’, 1); |
21 |
– $sql = $select ->assemble(); |
23 |
return $this ->_getReadAdapter()->fetchAll( $select ); |
Magento操 作数据库是在 Zend DB(Zend Framework)的基础上简单的做了下封装了。Zend DB 有自己的一套规则,来组合生成最终的SQL查询语句,可以看到上面的代码中有 from() join() joinLeft() where() 等函数,乱七八糟的一大堆东西,需要对 Zend DB的规则非常熟悉,才能知道实际执行的SQL语句,有没有办法直接打印出SQL语句?找了下,还真有,就是assemble()函数。在上面代码中最后 部分可以看到。顺被把SQL也附上来
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语句