Magento在addAttributeToFilter中如何使用条件
addAttributeToFilter是一个可以在Magento产品集合调用的函数。简言之,它添加到WHERE条件的MySQL查询的一部分用于从数据库中提取的产品集合。
$_products = Mage::getModel('catalog/product')->getCollection()
->addAttributeToSelect(array('name', 'product_url', 'small_image'))
->addAttributeToFilter('sku', array('like' => 'UX%'))
->load();
上面的代码,会得到一个产品的集合,每个产品有它的名字,网址,价格和小的图像,它的数据阵列中装入。通过一个SKU以UX进模糊查询,该产品将收集过滤,包含唯一的产品。
addAttributeToFilter条件语句
注意上面,我使用LIKE运算符?有在SQL和addAttributeToFilter许多的字段都可以使用。包括以下以及供您参考。希望这会节省你一些时间。
等于:eq
$_products->addAttributeToFilter('status', array('eq' => 1));
不等于: neq
$_products->addAttributeToFilter('sku', array('neq' => 'test-product'));
Like:like
$_products->addAttributeToFilter('sku', array('like' => 'UX%'));
注意like是可以包含SQL通配符,如百分号。
Not Like:nlike
$_products->addAttributeToFilter('sku', array('nlike' => 'err-prod%'));
In:in
$_products->addAttributeToFilter('id', array('in' => array(1,4,74,98)));
参数还可以接受一个数组的值。
Not In:nin
$_products->addAttributeToFilter('id', array('nin' => array(1,4,74,98)));
NULL:null
$_products->addAttributeToFilter('description', 'null');
Not NULL:notnull
$_products->addAttributeToFilter('description', 'notnull');
大于:gt
$_products->addAttributeToFilter('id', array('gt' => 5));
小于:lt
$_products->addAttributeToFilter('id', array('lt' => 5));
大于或等于:gteq
$_products->addAttributeToFilter('id', array('gteq' => 5));
小于或等于: lteq
$_products->addAttributeToFilter('id', array('lteq' => 5));
addFieldToFilter()
据我所知,addAttributeToFilter只适用于在Magento产品。当我第一次发现了这个事实,我不仅感到震惊,我很担心!我想,没有它,我将有我所有的SQL查询定制工艺。找Magento的核心代码后,我发现addFieldToFilter()。这个功能,在相同的方式工作,并采用相同的参数研究,但它适用于所有集合,不只是产品!
关于addFieldToFilter()的一些用法请看:http://www.magentocommerce.com/wiki/1_-_installation_and_configuration/using_collections_in_magento
调试SQL查询
有两种方法调试加载在Magento集合时正在执行的查询。
// Method 1
Mage::getModel('catalog/product')->getCollection()->load(true);
// Method 2 (Quicker, Recommended)
$collection = Mage::getModel('catalog/product')->getCollection();
echo $collection->getSelect();
方法1和方法2都是打印查询的,但各自有略微不同的方式。方法1,打印查询以及装载产品,而方法2将只查询对象转换为一个字符串(即会打印出的SQL语句)。第二种方法是肯定更好,更快,因为它会被执行,但我有参考他们都在这里。
在一个侧面说明,我将很快被写上getSelect()函数的文章,因为它开辟了一个门在Magento集合,让他们(和你)真正的力量!
浙公网安备 33010602011771号