1

I am using magento 2.3.3 i have custom module in that i am using search when any one search i am filter products name like it is working fine but now i want add extra attributes.I have created product attribute product_title as text field not required.

I have created 2 products

one name=>test.

second one is name=>text ,product_title=>7986

when customer search test key work no results found.

$collection = $this->_productCollection
                     ->create()
                     ->addFieldToSelect('*')
                     ->addFieldToFilter('name', ['like' => '%'.$queryString.'%']);

if i use above code with name filter it showing result

$collection = $this->_productCollection
                                    ->create()
                                    ->addFieldToSelect('*')
                                    //->addFieldToFilter('name', ['like' => '%'.$queryString.'%'])
                                    ->addAttributeToFilter(
                                    array(
                                            array('attribute' => 'name', 'like', '%' . $queryString . '%'),
                                            array('attribute' => 'oem_no','like', '%' . $queryString . '%')
                                        ),
                                     );

if i use both filter no result 0 records.

My requirement i need to search search key word with both attributes if match keyword name or product_title need get that result

 SELECT `e`.*,`v`.`entity_id`,`v`.`attribute_id`,`v`.`value` FROM `catalog_product_entity` AS `e` JOIN `catalog_product_entity_varchar` as `v` on `v`.`entity_id` = `e`.`entity_id` WHERE `v`.`attribute_id` IN (70,195) AND `value` LIKE '%test%'

this raw query getting result in phpmyadmin same like this need result

this is my complete file

    <?php
/**
 * Webkul Software.
 *
 * @category  Webkul
 * @package   Webkul_MpAssignProduct
 * @author    Webkul
 * @copyright Copyright (c) Webkul Software Private Limited (https://webkul.com)
 * @license   https://store.webkul.com/license.html
 */
namespace Webkul\MpAssignProduct\Block\Product;

use Magento\Catalog\Model\ResourceModel\Product\CollectionFactory as ProductCollection;
use Webkul\Marketplace\Model\ResourceModel\Product\CollectionFactory;
use Webkul\MpAssignProduct\Model\ResourceModel\Items\CollectionFactory as AssignProductCollection;

class ProductList extends \Magento\Framework\View\Element\Template
{
    /**
     * @var \Magento\Store\Model\StoreManagerInterface
     */
    protected $_storeManager;

    /**
     * @var \Magento\Customer\Model\Session
     */
    protected $_customerSession;

    /**
     * @var \Webkul\MpAssignProduct\Helper\Data
     */
    protected $_assignHelper;

    /**
     * @var ProductCollection
     */
    protected $_productCollection;
    
    /**
     * @var AssignProductCollection
     */
    protected $_assignProductCollection;

    /**
     * @var CollectionFactory
     */
    protected $_mpProductCollection;

    /**
     * @var \Magento\Catalog\Model\Product\Attribute\Source\Status
     */
    protected $_productStatus;

    /**
     * @var \Magento\Catalog\Model\Product\Visibility
     */
    protected $_productVisibility;

    /**
     * @var \Magento\Catalog\Model\ResourceModel\Product\Collection
     */
    protected $_productList;

    /**
     * @param \Magento\Catalog\Block\Product\Context $context
     * @param \Magento\Customer\Model\Session $customerSession
     * @param \Webkul\MpAssignProduct\Helper\Data $helper
     * @param ProductCollection $productCollectionFactory
     * @param CollectionFactory $mpProductCollectionFactory
     * @param \Magento\Catalog\Model\Product\Attribute\Source\Status $productStatus
     * @param \Magento\Catalog\Model\Product\Visibility $productVisibility
     * @param array $data
     */
    public function __construct(
        \Magento\Catalog\Block\Product\Context $context,
        \Magento\Customer\Model\Session $customerSession,
        \Webkul\MpAssignProduct\Helper\Data $helper,
        ProductCollection $productCollectionFactory,
        CollectionFactory $mpProductCollectionFactory,
        \Magento\Catalog\Model\Product\Attribute\Source\Status $productStatus,
        \Magento\Catalog\Model\Product\Visibility $productVisibility,
        AssignProductCollection $assignProductCollection,
        \Magento\Eav\Model\ResourceModel\Entity\Attribute $eavAttribute,
        array $data = []
    ) {
        $this->_storeManager = $context->getStoreManager();
        $this->_customerSession = $customerSession;
        $this->_assignHelper = $helper;
        $this->_productCollection = $productCollectionFactory;
        $this->_mpProductCollection = $mpProductCollectionFactory;
        $this->_productStatus = $productStatus;
        $this->_productVisibility = $productVisibility;
        $this->_assignProductCollection = $assignProductCollection;
        $this->_eavAttribute = $eavAttribute;
        parent::__construct($context, $data);
    }

    /**
     */
    protected function _construct()
    {
        parent::_construct();
        $this->pageConfig->getTitle()->set(__('My Product List'));
    }

    /**
     * @return bool|\Magento\Catalog\Model\ResourceModel\Product\Collection
     */
    public function getAllProducts()
    {
        if (!$this->_productList) {
            $queryString = $this->_assignHelper->getQueryString();
            $page=($this->getRequest()->getParam('p'))? $this->getRequest()->getParam('p') : 1;
            $pageSize=($this->getRequest()->getParam('limit'))? $this->getRequest()->getParam('limit') : 1;

            if ($queryString != '') {
                $customerId = $this->_customerSession->getCustomerId();
                $sellercollection = $this->_mpProductCollection
                                        ->create()
                                        ->addFieldToFilter('seller_id', ['eq' => $customerId])
                                        ->addFieldToSelect('mageproduct_id');
                $products = [];
                foreach ($sellercollection as $data) {
                    array_push($products, $data->getMageproductId());
                }
                $sellerAssigncollection = $this->_assignProductCollection
                                ->create()
                                ->addFieldToFilter('seller_id', $customerId)
                                ->addFieldToSelect('product_id');
                foreach ($sellerAssigncollection as $data) {
                    array_push($products, $data->getProductId());
                }

                $allowedTypes = $this->_assignHelper->getAllowedProductTypes();
                $collection = $this->_productCollection
                                    ->create()
                                    ->addFieldToSelect('*')
                                    //->addFieldToFilter('name', ['like' => '%'.$queryString.'%']);
                                    ->addFieldToFilter('name', ['like' => '%'.$queryString.'%'])->addFieldToFilter('oem_no', ['like' => '%'.$queryString.'%']);
//                                    ->addAttributeToFilter(
//                                    array(
//                                            //array('attribute' => 'name', 'like', '%' . $queryString . '%'),
//                                            array('attribute' => 'oem_no','like', '%' . $queryString . '%')
//                                        ),
//                                        '',
//                                        'left'
//                                    );
                echo $collection->getSelect();
                                echo count($collection);
//                                foreach ($collection as $collections){
//                                    print_r("sdkjfhdskjhf".$collections->getData());
//                                }
                $attributeId = $this->_eavAttribute->getIdByCode('catalog_product', 'oem_no');
                print_r($attributeId);
                die("here");
                //$collection->joinField('category_id', 'catalog/category_product', 'category_id', 'product_id = entity_id', null, 'left');
                $collection->addFieldToFilter('type_id', ['in' => $allowedTypes]);
                if (count($products) > 0) {
                    $collection->addFieldToFilter('entity_id', ['nin' => $products]);
                }
                $collection->addAttributeToFilter('status', ['in' => $this->_productStatus->getVisibleStatusIds()]);
                $collection->setVisibility($this->_productVisibility->getVisibleInSiteIds());
                $collection->setOrder('created_at', 'desc');
            } else {
                $collection = $this->_productCollection
                                    ->create()
                                    ->addFieldToSelect('*')
                                    ->addFieldToFilter('entity_id', 0);
            }
            $collection->setPageSize($pageSize);
            $collection->setCurPage($page);
            $this->_productList = $collection;
        }
        return $this->_productList;
    }

    /**
     * @return $this
     */
    protected function _prepareLayout()
    {
        parent::_prepareLayout();
        if ($this->getAllProducts()) {
            $pager = $this->getLayout()->createBlock(
                \Magento\Theme\Block\Html\Pager::class,
                'mpassignproduct.product.list.pager'
            )
            ->setShowPerPage(true)
            ->setCollection(
                $this->getAllProducts()
            );
            $this->setChild('pager', $pager);
            $this->getAllProducts()->load();
        }

        return $this;
    }

    /**
     * @return string
     */
    public function getPagerHtml()
    {
        return $this->getChildHtml('pager');
    }

    /**
     * Get Current Currency Symbol
     *
     * @return string
     */
    public function getCurrencySymbol()
    {
        $symbol = $this->_storeManager->getStore()->getBaseCurrencyCode();
        return $symbol;
    }
}

can any one give solution how to get result

0

If you just need an and operation you can call addFieldToFilter twice to get the result as follows;

$collection = $this->_productCollection
                 ->create()
                 ->addFieldToSelect('*')
                 ->addFieldToFilter('name', ['like' => '%'.$queryString.'%'])->addFieldToFilter('product_title', ['like' => '%'.$queryString.'%']);
| improve this answer | |
  • i alredy tried but no getting result count is 0.search key word need to check name and product title if match any field get result – Pawankumar Jul 12 at 4:31
  • i think given answer is like and conditions i need or keyword exist name or title we need to get data – Pawankumar Jul 12 at 4:39

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.