首页 文章

Magento 2 - 过滤集合,用于多选定制产品属性

提问于
浏览
3

我是Magento 2的新手,我有一个自定义模块,它使用插件来改变目录模型层中的产品集合 . 我使用以下选项为产品创建了一个多选定制属性:

backend => '\Magento\Eav\Model\Entity\Attribute\Backend\ArrayBackend'

它成功地创建,填充和保存多选字段及其来自编辑产品表单的数据 . 我也能够毫无问题地从多选数组中获取所有值:

$product->getAllAttributeValues('my_custom_attribute');

这打印出如下内容:

Array
(
    [18] => Array
    (
        [0] => 1,3,4
    )

    [14] => Array
    (
        [0] => 
    )

    [32] => Array
    (
        [0] => 3,8
    )
)

So here's my problem:

假设我有一个变量

$value = "3"

我只想在my_custom_attribute中显示具有$ value的产品 . 在上面的示例中,仅显示[18]和[32] .

有没有办法使用addAttributeToFilter()方法在Magento 2中执行此操作?

例如:

$product->addAttributeToFilter('my_custom_attribute', $value);

EDIT: 有没有办法在数组上做"nin"(不在),这样如果$ value = 1,只会显示[14]和[32]?例如:

$value = 1;
$product->addAttributeToFilter('my_custom_attribute', array('nin' => $value))

1 回答

  • 1

    注意:这个问题的目的是找出是否有新的Magento 2方法,但经过几天的搜索和缺乏回应后,我空手而归 . 所以这个答案是基于我对Magento 1.x的经验 . 它适用于Magento 2,但可能有更合适的方法 .

    这是我的解决方案:

    /**
     * @param $product
     * @return mixed
     */
    public function filterProducts($product) {
        $attributeValues = $product->getAllAttributeValues('my_custom_attribute');
    
        foreach($attributeValues as $entity_id => $value) {
            if($this->_isItemHidden($value[0])) {
                $this->_removeCollectionItems($product, $entity_id);
            }
        }
    
        return $product;
    }
    
    /**
     * @return int
     */
    protected function _getCustomValue() {
        return '3';
    }
    
    /**
     * @param $string
     * @return bool
     */
    protected function _isItemHidden($string) {
    
        $customValue= $this->_getCustomValue();
    
        $multiselectArray= explode(',', $string);
    
        foreach($multiselectArray as $value) {
            if($value== $customValue){
                return true;
            }
        }
        return false;
    }
    
    /**
     * @param $collection
     * @param $customValue
     */
    protected function _removeCollectionItems($collection, $entity_id)
    {
        $collection->addAttributeToFilter('entity_id', array('nin' => $entity_id));
    }
    

    其中$ this - > _ getCustomValue()==您试图包含或排除的任何值 .

    所以从我的插件中,filterProducts()被调用传入原始函数的返回值 .

相关问题