addFieldToFilter 与 addAttributeToFilter使用总结

转载自: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的继承关系):

[php]  view plain copy
  1. public function addAttributeToFilter($attribute$condition = null)  
  2. {  
  3.     $this->addFieldToFilter($this->_attributeToField($attribute), $condition);  
  4.     return $this;  
  5. }  
  6.   
  7. /** 
  8.  * Check if $attribute is Mage_Eav_Model_Entity_Attribute and convert to string field name 
  9.  * 
  10.  * @param string|Mage_Eav_Model_Entity_Attribute $attribute 
  11.  * @return string 
  12.  */  
  13. protected function _attributeToField($attribute)  
  14. {  
  15.     $field = false;  
  16.     if (is_string($attribute)) {  
  17.         $field = $attribute;  
  18.     } elseif ($attribute instanceof Mage_Eav_Model_Entity_Attribute) {  
  19.         $field = $attribute->getAttributeCode();  
  20.     }  
  21.     if (!$field) {  
  22.         Mage::throwException(Mage::helper('yourmode')->__('Cannot determine the field name.'));  
  23.     }  
  24.     return $field;  
  25. }  
magento自带的模块涉及到EAV模型的collection最终都是继承自Mage_Eav_Model_Entity_Collection_Abstract,如catalog,customer模块等,这个类定义了很多有用的function,包括addAttributeToFilter等,读者可自行去深入了解。
总结:addFieldToFilter基本上是addAttributeToFilter的别名,很多时候能通用;对用自定义的模块,一般使用addFieldToFilter就能满足需求。对于EAV模型,大多都是系统自带模块,addAttributeToFilter就显得很有用。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值