转载自:http://blog.csdn.net/shangxiaoxue/article/details/7108106
magento初学者在开发过程中,对addFieldToFilter和addAttributeToFilter的使用会比较迷惑,例如你在一个自定义模块中,在引用自己的table时,假如使用了addAttributeToFilter这个function,可能就会报错。
简单分析下原因:
我们在自定义模块里的collection类,因为没有涉及到EAV模型,一般都是继承Mage_Core_Model_Mysql4_Collection_Abstract这个类,而在Mage_Core_Model_Mysql4_Collection_Abstract(继承自Varien_Data_Collection_Db包含很多常用function)和它的父类里,是没有addAttributeToFilter这个function的,如果一定要使用addAttributeToFilter可以在collection加上如下function(或者改变collection的继承关系):
- public function addAttributeToFilter($attribute, $condition = null)
- {
- $this->addFieldToFilter($this->_attributeToField($attribute), $condition);
- return $this;
- }
- /**
- * Check if $attribute is Mage_Eav_Model_Entity_Attribute and convert to string field name
- *
- * @param string|Mage_Eav_Model_Entity_Attribute $attribute
- * @return string
- */
- protected function _attributeToField($attribute)
- {
- $field = false;
- if (is_string($attribute)) {
- $field = $attribute;
- } elseif ($attribute instanceof Mage_Eav_Model_Entity_Attribute) {
- $field = $attribute->getAttributeCode();
- }
- if (!$field) {
- Mage::throwException(Mage::helper('yourmode')->__('Cannot determine the field name.'));
- }
- return $field;
- }
总结:addFieldToFilter基本上是addAttributeToFilter的别名,很多时候能通用;对用自定义的模块,一般使用addFieldToFilter就能满足需求。对于EAV模型,大多都是系统自带模块,addAttributeToFilter就显得很有用。