我是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 回答
注意:这个问题的目的是找出是否有新的Magento 2方法,但经过几天的搜索和缺乏回应后,我空手而归 . 所以这个答案是基于我对Magento 1.x的经验 . 它适用于Magento 2,但可能有更合适的方法 .
这是我的解决方案:
其中$ this - > _ getCustomValue()==您试图包含或排除的任何值 .
所以从我的插件中,filterProducts()被调用传入原始函数的返回值 .