且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Magento:使用分组子句过滤集合

更新时间:2023-11-30 10:05:40

如果您的集合是 EAV 类型,那么这很有效:

If your collection is an EAV type then this works well:

$collection = Mage::getResourceModel('yourmodule/model_collection')
    ->addAttributeToFilter('col1', 'x')
    ->addAttributeToFilter(array(
        array('attribute'=>'col2', 'eq'=>'y'),
        array('attribute'=>'col3', 'eq'=>'z'),
    ));

但是,如果您坚持使用平面表格,我不认为 addFieldToFilter 的工作方式完全相同.一种替代方法是直接使用选择对象.

However if you're stuck with a flat table I don't think addFieldToFilter works in quite the same way. One alternative is to use the select object directly.

$collection = Mage::getResourceModel('yourmodule/model_collection')
    ->addFieldToFilter('col1', 'x');
$collection->getSelect()
    ->where('col2 = ?', 'y')
    ->orWhere('col3 = ?', 'z');

但是这个的失败是操作符的顺序.您将得到类似 SELECT * FROM my_table WHERE (col1='x') AND (col2='y') OR (col3='z') 的查询.OR 在这里不优先,绕过它意味着更具体......

But the failing of this is the order of operators. You willl get a query like SELECT * FROM my_table WHERE (col1='x') AND (col2='y') OR (col3='z'). The OR doesn't take precedence here, to get around it means being more specific...

$collection = Mage::getResourceModel('yourmodule/model_collection')
    ->addFieldToFilter('col1', 'x');
$select = $collection->getSelect();
$adapter = $select->getAdapter();
$select->where(sprintf('(col2 = %s) OR (col3 = %s)', $adapter->quote('x'), $adapter->quote('y')));

传递不带引号的值是不安全的,这里使用适配器来安全地引用它们.

It is unsafe to pass values unquoted, here the adapter is being used to safely quote them.

最后,如果 col2col3 实际上相同,如果您对单列中的值进行 OR 运算,那么您可以使用以下简写:

Finally, if col2 and col3 are actually the same, if you're OR-ing for values within a single column, then you can use this shorthand:

$collection = Mage::getResourceModel('yourmodule/model_collection')
    ->addFieldToFilter('col1', 'x')
    ->addFieldToFilter('col2', 'in'=>array('y', 'z'));