2

I need to known how to use addFieldToFilter & addFieldToSelect in frontend? And can I use like below

$searchQuery = $wholeData["searchQuery"] ?? "";
$searchQuery = trim($searchQuery);
$agentCollection = $this->_agents->create()->addNameToSelect();
             
if ($agentId > 0) {
    $agentCollection->addFieldToFilter("id", $agentId);
} else {
    $agentCollection->addFieldToSelect("email")
            ->addFieldToFilter(
                    [
                            ["field"=>"email", "like"=>"%".$searchQuery."%"],
                            ["field"=>"contactno", "like"=>"%".$searchQuery."%"]
                    ]
            );
}

3 Answers 3

0

1) yes you can use this logic in front end but in block classes. 2) yes above logic can be used but it will add OR logic in you case same as following in better way

$this->collection->addFieldToFilter(
        ['weight', 'name'],
        [['in' => [1, 3]], ['like' => 'M%']]
    );

Can be used as AND logic:

$category = $this->collectionFactory->create()
            ->addFieldToFilter('parent_id', $rootCategoryId)
            ->addFieldToFilter('name', $categoryName)
            ->fetchItem();
7
  • what is this addFieldToFilter Nov 12, 2019 at 16:58
  • addFieldToFilter is similar to sql part : where name = 'hassan' Nov 12, 2019 at 19:37
  • SELECT time FROM list WHERE date = "2020-10-12" GROUP BY time; HOw would you do this? Nov 13, 2019 at 9:00
  • $collection = $this->collectionFactory->create(); $collection->addAttributeToSelect('*'); $collection->addAttributeToFilter('date', $date); $collection->getSelect()->reset(\Zend_Db_Select::COLUMNS) ->columns('time'); $collection->getSelect()->group('time'); git it from here magento.stackexchange.com/questions/295358/… Nov 13, 2019 at 9:01
  • what are you doing? in above you are collecting all attributes by using * and the reset again all element and select 'time'. why don't you put $collection->addAttributeToSelect('time'); ? Nov 13, 2019 at 9:10
0

Followings are my findings about your question:

  1. What does "use addFieldToFilter & addFieldToSelect in frontend." means?
  2. Yes, you can use addFieldToFilter as you define.
    • If email column is in your table, then you don't need to add email in to select.
    • Use Add field to select when you are using this with the select column in another table when joining.
0

You can use addFieldToFilter to filter collection data by any available field

Due to performance reasons most collections won't include all fields by default, so you may use addFieldToSelect to add the fields you need

For instance, the code in the question adds email to collection, so it's included and then it's available to filter the collection

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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