4
$collectionData = $this->_productCollectionFactory->create()->addAttributeToSelect('*')
    ->addFieldToFilter(['attribute1', 'attribute2'],
        [
            ['in' => $attribute1],
            ['nin' => $attribute2],
        ]);

I want to get collection based on "OR condition" on three attribute for example a product which has color yellow or size small but not manufacture china.

  • is this collection is EAV collection or flat collection – Amit Bera Dec 30 '16 at 14:12
  • getting data from product collection – chin Dec 30 '16 at 14:17
  • 1
    use addAttributeToFilter() instead of addFieldToFilter – Amit Bera Dec 30 '16 at 14:21
15

I assume that in your example, yellow, small and china are options in dropdowns.
You will need their ids first, but let's assume the are $yellowId, $smallId and $chinaId.

You can try this filtering.

->addFieldToFilter(['color', 'size', 'country'],
    [
        ['eq' => $yellowId],
        ['eq' => $smallId],
        ['neq' => $chinaId]
    ]);
5

This should give you all items that are not made in china and that have either color yellow or size small:

$collection
    ->addFieldToFilter('manufacturer', ['neq' => $chinaId])
    ->addFieldToFilter(
        ['color', 'size'],
        [
            ['eq' => $yellowId],
            ['eq' => $smallId]
        ]
);
4

From the description of the method: \Magento\Eav\Model\Entity\Collection\AbstractCollection::addAttributeToFilter which is the same with addFieldToFilter method from the same class. Product entity is implemented with EAV.

// If $attribute is an array will add OR condition with following format:
array(
   array('attribute'=>'firstname', 'like'=>'test%'),
   array('attribute'=>'lastname', 'like'=>'test%'),
)
public function addAttributeToFilter($attribute, $condition = null, $joinType = 'inner')
{
...
}
  • This is the only method that worked form me – Char Dec 21 '17 at 14:34
  • Aaron Allen answer did not work for me, the above did. – George Donev Nov 14 '18 at 21:45
0

Try this, It work for me

$collection->addAttributeToFilter([
     ['attribute' => 'attribute1','null' => true ],
     ['attribute' => 'attribute1','gteq' => 1 ]
]);
    // Don't change 'attribute', It will be used at AbstractCollection: 373
    // WHERE attribute1 = NULL OR attribute1 >= 1
New contributor
Châu Văn Khánh Nhật is a new contributor to this site. Take care in asking for clarification, commenting, and answering. Check out our Code of Conduct.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.