Magento 操作数据库是在 Zend DB(Zend Framework)的基础上简单的做了下封装了。Zend DB 有自己的一套规则,来组合生成最终的SQL查询语句,可以看到上面的代码中有 from() join() joinLeft() where() 等函数,乱七八糟的一大堆东西,需要对 Zend DB的规则非常熟悉,才能知道实际执行的SQL语句,有没有办法直接打印出SQL语句?找了下,还真有,就是assemble()函数。在上面代码中最后部分可以看到。
今天在分析Magento源代码的时候,在文件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); }
输出结果:
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)
转载请注明出处:https://www.onexin.net/magento-teach-you-to-understand-the-sql-statement/