【问题标题】:Magento: Adding more than one 'Tag' to a collection filterMagento:向集合过滤器添加多个“标签”
【发布时间】:2013-01-05 23:54:49
【问题描述】:

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

relation.tag_id = 6 AND relation.tag_id = 9

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

$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 }

}

【问题讨论】:

    标签: php sql magento


    【解决方案1】:

    查看此代码

    $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

    【讨论】:

    • 谢谢阿米特,这种方式基本上和我上面的代码做同样的事情,我可以在 SELECT 中看到两者都添加了 AND SQL,但它仍然不会选择正确的结果,也许它有一些事情要做用它收集相关标签的方式?! :s
    猜你喜欢
    • 1970-01-01
    • 2012-07-20
    • 2012-03-13
    • 1970-01-01
    • 2011-08-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-09
    相关资源
    最近更新 更多