Magento:向集合过滤器添加多个“标签”


Magento: Adding more than one 'Tag' to a collection filter

这是一个漫长的周末,我的大脑无法工作,我正在尝试通过多个标签过滤产品集合。在"tag/product_collection"上,我只能向"addTagFilter"提供一个值,所以我试图将我自己的语句传递给where()

relation.tag_id = 6 AND relation.tag_id = 9

但它没有返回,即使有 6 个产品同时具有标签 6 和 9,我也可以将查询更改为 IN (6,9),它返回所有具有 AND 的产品并删除 AND 并选择说只有 6 或 9 工作正常,但对于我的生活,我无法弄清楚为什么 AND 不返回?!完整代码如下。

$collection = Mage::getResourceModel('tag/product_collection');
$collection->addAttributeToFilter('status', array('eq' => 1));
$collection->addAttributeToFilter('type_id','simple');
$collection->addAttributeToSelect('sku')
    ->addAttributeToSelect('name')
    ->getSelect()->where("relation.tag_id = 6 AND relation.tag_id = 9","");  

提前谢谢。

=== 编辑 ===好吧,好吧,我没有太多运气试图在集合上找出"SQL"方式,所以如果有人找到一个,请随时在下面列出它,我们都会投票赞成它。与此同时,我有一种有点笨拙的方式。如果你有 1000 种产品,我不会推荐这个,我可以想象它有点慢。

// Load our collection
$collection = Mage::getResourceModel('tag/product_collection');
$collection->addAttributeToFilter('status', array('eq' => 1));
$collection->addAttributeToFilter('type_id','simple');
$collection->addAttributeToSelect('sku')
->addAttributeToSelect('name');
// Loop the collection  
foreach ( $collection as $_product)
    {   
    // Load ALL tags for product
    $model = Mage::getModel('tag/tag');
    $tags = $model->getResourceCollection()
        ->addPopularity()
        ->addStatusFilter($model->getApprovedStatus())
        ->addProductFilter($_product->getId())
        ->setFlag('relation', true)
        ->addStoreFilter(Mage::app()->getStore()->getId())
        ->setActiveFilter()
        ->load();
    // loop through all the tags if we find one set a flag to skip returning this product.
    $arr = array();
    foreach($tags as $_t){ $arr[$_t->getId()] = $_t->getName(); }
    $filter_tags = count($_REQUEST['tags']) > 0 ? $_REQUEST['tags'] : array();
    $tag_found = 0;
    $on_filter =  count($filter_tags) > 0 ? 1 : 0;
    foreach($arr as $key => $value){ array_key_exists($key,$filter_tags) ? $tag_found++ : 0; }
    // if all if good send the product to an array to be returned
    if($on_filter && $tag_found){ // add $_product to a return }
}

查看此代码

$collection = Mage::getResourceModel('tag/product_collection');
$collection->addAttributeToFilter('status', array('eq' => 1));
$collection->addAttributeToFilter('type_id','simple');
$collection->addAttributeToSelect('sku')
    ->addAttributeToSelect('name')
    ->getSelect()->Where('relation.tag_id=?', 6)
        ->Where('relation.tag_id=?', 9);

你可以把多个 where 类放在一起,默认情况下它会添加"AND",如果你想要"OR"那么你可以使用 orWhere 而不是Where