繁体   English   中英

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]。

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

例如:

$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()被调用传入原始函数的返回值。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM