magento初学者在开发过程中,对addFieldToFilter和addAttributeToFilter的使用会比较迷惑,例如你在一个自定义模块中,在引用自己的table时,假如使用了addAttributeToFilter这个function,可能就会报错。
简单分析下原因:
<p>我们在自定义模块里的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的继承关系):</p><p>
</p><p><span style="font-size:18px;color:#FF0000;"><strong><span><span>addFieldToFilter</span></span></strong></span>
</p>
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;
}
记录一下Magento模型集合Model Collection中addFieldToFilter()方法常用的过滤条件。以下参数也同样适用于产品实体的addAttributeToFilter()方法。
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
|
//Equals: eq
$_products
->addAttributeToFilter(
'status'
,
array
(
'eq'
=> 1));
//Not Equals - neq
$_products
->addAttributeToFilter(
'sku'
,
array
(
'neq'
=>
'test-product'
));
//Like - like
$_products
->addAttributeToFilter(
'sku'
,
array
(
'like'
=>
'UX%'
));
//Not Like - nlike
$_products
->addAttributeToFilter(
'sku'
,
array
(
'nlike'
=>
'err-prod%'
));
//In - in
$_products
->addAttributeToFilter(
'id'
,
array
(
'in'
=>
array
(1,4,98)));
//Not In - nin
$_products
->addAttributeToFilter(
'id'
,
array
(
'nin'
=>
array
(1,4,98)));
//NULL - null
$_products
->addAttributeToFilter(
'description'
,
'null'
);
//Not NULL - notnull
$_products
->addAttributeToFilter(
'description'
,
'notnull'
);
//Greater Than - gt
$_products
->addAttributeToFilter(
'id'
,
array
(
'gt'
=> 5));
//Less Than - lt
$_products
->addAttributeToFilter(
'id'
,
array
(
'lt'
=> 5));
//Greater Than or Equals To- gteq
$_products
->addAttributeToFilter(
'id'
,
array
(
'gteq'
=> 5));
//Less Than or Equals To - lteq
$_products
->addAttributeToFilter(
'id'
,
array
(
'lteq'
=> 5));
|
SQL的DEBUG方法
01
02
03
04
05
06
|
// 第一种,该方法货执行load的过程
Mage::getModel(
'catalog/product'
)->getCollection()->load(true);
// 第二种,该方法不会执行load过程,只把sql语句转换为string对象。
$collection
= Mage::getModel(
'catalog/product'
)->getCollection();
echo
$collection
->getSelect();
|
懒省事了,转载地址:
http://fishpig.co.uk/blog/addattributetofilter-conditionals-in-magent