For example, the search query is 'samsung lcd'. it can match with product name or SKU.
I have below product names.
1.samsung xyz lcd.
2.samsung lcd pack.
3.samsung mobile
4.screen lcd.
so when I filter I need to get only
1.samsung xyz lcd.
2.samsung lcd pack.
where name like '%samsung lcd%' or sku like '%samsung lcd%' or (name like '%samsung%' or sku like '%samsung%' and(name like '%lcd%' or sku like '%lcd%'))
but now I'm getting all above product names. Could you please help me with this.
$term = $this->getRequest()->getParam('term');
$termArr = explode(' ', $term);
$search = array();
$search[] = array('attribute' => 'sku', 'like' => '%' . $term . '%');
$search[] = array('attribute' => 'name', 'like' => '%' . $term . '%');
foreach ($termArr as $termc) {
$search[] = array(
'attribute' => 'name', 'like' => '%' . $termc . '%');
$search[] = array(
'attribute' => 'sku', 'like' => '%' . $termc . '%');
}
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$collection = $objectManager->create('\Magento\Catalog\Model\ResourceModel\Product\CollectionFactory')->create();
$collection->addAttributeToSelect('name');
$collection->addFieldToFilter($search);
$collection->addAttributeToFilter('status',\Magento\Catalog\Model\Product\Attribute\Source\Status::STATUS_ENABLED);
$collection->setPageSize(10);
update: The following code is working fine, but not optimized.
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$term = $this->getRequest()->getParam('term');
$termArr = explode(' ', $term);
$pids = array();
if (count($termArr)) {
$collection1 = $objectManager->create('\Magento\Catalog\Model\ResourceModel\Product\CollectionFactory')->create();
foreach ($termArr as $termc) {
$termc = trim($termc);
if ($termc == '')
continue;
$search1 = array();
$search1[] = array(
'attribute' => 'name', 'like' => '%' . $termc . '%');
$search1[] = array(
'attribute' => 'sku', 'like' => '%' . $termc . '%');
$collection1->addFieldToFilter($search1);
}
$collection1->getSelect()->reset(\Zend_Db_Select::COLUMNS);
$collection1->getSelect()->columns(['entity_id']);
$pids = $collection1->getAllIds();
}
$collection = $objectManager->create('\Magento\Catalog\Model\ResourceModel\Product\CollectionFactory')->create();
$collection->addAttributeToSelect('name');
$search = array();
$search[] = array('attribute' => 'sku', 'like' => '%' . $term . '%');
$search[] = array('attribute' => 'name', 'like' => '%' . $term . '%');
if (count($pids)) {
$search[] = array('attribute' => 'entity_id', 'in' => $pids);
}
$collection->addFieldToFilter($search);
$collection->addAttributeToFilter('status', \Magento\Catalog\Model\Product\Attribute\Source\Status::STATUS_ENABLED);
$collection->setPageSize(10);