这是一个漫长的周末,我的大脑无法正常工作,我正在尝试通过多个标签过滤产品集合。在“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 }
}