-1

I am trying to use AND and OR based on user input.

OR = success

But I an unable to setup AND queries for addFieldToFilter

question: how can I add the second (looped filter) using AND to join

$search_array = array();
$or_array = array();
if (is_numeric($query)) {
    // this becomes OR and is great
    $search_array[] = array('attribute' => 'entity_id', 'eq' => $query);
    $search_array[] = array('attribute' => 'sku', 'like'=>'%'.$query.'%');
} else {

    if (strpos($query, ' ') !== false) {
        $morewords = explode(" ", $query);
        foreach ($morewords as $word) {
            // This needs to be AND clause - need help
            $search_array[] = array('attribute' => 'sku', 'like'=>'%'.$word.'%');
        }
    } else {
            $search_array[] = array('attribute' => 'sku', 'like'=>'%'.$query.'%');
    }
}

    $collection->addFieldToFilter($search_array);
0

Check below code for AND condition

protected $_customer;
protected $_customerFactory;

public function __construct(
...
\Magento\Customer\Model\CustomerFactory $customerFactory,
\Magento\Customer\Model\Customer $customers
...) {
...
$this->_customerFactory = $customerFactory;
$this->_customer = $customers;
...
}

public function execute() {
...
        $collection = $this->_customerFactory->create()->getCollection()
                ->addAttributeToSelect("*")
                ->addFieldToFilter("email", array("eq" => "test1@mailinator.com"))
                ->addFieldToFilter('store_id', array('eq' => 1));
        echo (string)$collection->getSelect();
        exit;
...
}

the expected query result is SELECTe.* FROMcustomer_entityASeWHERE (e.email= 'test1@mailinator.com') AND (e.store_id= 1)

  • Can I add the filter call in a foreach loop?? – snh_nl Dec 1 '18 at 12:25
  • if you want to put filter query into foreach then put like $collection->addFieldToFilter("email", array("eq" => "test1@mailinator.com")); in foreach. not your ways, in your ways your are like merging all filter into one it means it will run like OR condition not AND – Hitesh Dec 1 '18 at 12:29
  • Got fatal error every time when looping. Unknown attribute. Which is strange because it is right there. In the end used where condition for and and orwhere condition to add or condition in sql – snh_nl Dec 1 '18 at 18:30

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.