Magento 2 - 多选自定义产品属性的过滤器集合

Magento 2 - Filter collection for a multiselect custom product attribute

我是 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
    )
)

所以这是我的问题:

假设我有一个变量

$value = "3"

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

有没有办法在 Magento 2 中使用 addAttributeToFilter() 方法做到这一点?

例如:

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

编辑: 有没有办法在数组上也做一个 "nin" (不在),以便如果 $value = 1,只显示 [14] 和 [32]?例如:

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

注意:这个问题的目的是找出是否有一种新的 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() 被调用,从原始函数传入 return 值。