-1

addfieldtofilter in magento2 behaving weirdly

I have code

   foreach($userIDs as $singleUserID) {               
            $userid=$singleUserID['user_id'];
            var_dump($userid);//everytime for loop runs values changes 1,2,3
            $userDetails = $this->userCollection ->addFieldToFilter('user_id',$userid); 
            var_dump($userDetails->getData());/* output: array('id'=>1,'user_id'=>1,'user_name'=>'a'); 
                                array('id'=>1,'user_id'=>1,'user_name'=>'a'); 
                                array('id'=>1,'user_id'=>1,'user_name'=>'a');   */      
            }

same code If I write with passing value then it gives correct data

    foreach($userIDs as $singleUserID) {               
            $userid=$singleUserID['user_id'];
            var_dump($userid);//everytime for loop runs values changes 1,2,3

           // If I am passing direct value 1 or 2 or 3. getting correct data

          $userDetails = $this->userCollection->addFieldToFilter('user_id',3); 
            var_dump($userDetails->getData());/*output: array('id'=>1,'user_id'=>1,'user_name'=>'a');  for 1 
                   array('id'=>2,'user_id'=>2,'user_name'=>'b');   for 2
                   array('id'=>3,'user_id'=>3,'user_name'=>'c');   for 3 */      
            }
0

Now I able to get correct Data, I changed userCollection class to userCollectionfactory class

use Vendor\MyModule\Model\ResourceModel\Users\CollectionFactory as UserCollectionFactory;

Every time foreach runs User id changes and addFieldToFilter gives correct user details w.r.t userID

 foreach($userIDs as $singleUserID) {               
        $userid=$singleUserID['user_id'];
        var_dump($userid);//everytime values changes 1,2,3
        $userDetails = $this->userCollectionFactory->create() ->addFieldToFilter('user_id',$userid); 
        var_dump($userDetails->getData());// output: 
                            array('id'=>1,'user_id'=>1,'user_name'=>'a'); 
                            array('id'=>2,'user_id'=>2,'user_name'=>'b'); 
                            array('id'=>3,'user_id'=>3,'user_name'=>'c');         
        }
| improve this answer | |
  • Please do accept as an answer so others would use it – Prathap Gunasekaran Apr 17 '19 at 9: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.