0

I am having product collection where I am getting one custom product attribute called "keep_disabled" and another column which was added on runtime which is sum of quantities 'sum_qty'. I just want to get the product collection where keep disable is true and sum of quantity is greater than 0. I can filter out the quantity by :

$collection->getSelect()->having('sum_qty > 0');

but I also want to add filter :

$collection->addAttributeToFilter('keep_disabled', array(array('neq' => 1) , array('eq' => 0),array('null' => true)));

I only want those products where (if keep disable is false, don't check the quantity) and (if keep disable is true, get only those products where quantity is greater than 0); so basically don't want to show those products where keep disable is true and quantity is 0.

4
  • Try this one : $collection->addAttributeToFilter('keep_disabled',['eq' => 1]);$collection->getSelect()->having('sum_qty > 0'); – Rohan Hapani Jun 17 at 7:36
  • Hello @RohanHapani, from the first filter, it will filter out keep_disabled = 0, but as per my question, I want to keep keep disable = 0 as well. – Gaurav Harsh Jun 17 at 7:43
  • You mean you want keep_disabled 0 & 1 both records? – Rohan Hapani Jun 17 at 7:44
  • yes, if (keep_disable = false => get all records) + (keep_disable = true, get records where sum_qty is greater than 0). – Gaurav Harsh Jun 17 at 7:51
0

After struggling 2 days with MySql and Magento queries, I finally found the solution. As of my findings, I found out that this not possible with direct Magento query or direct MySql query but it can be possible by creating MySql VIEW table. I passed my mysql query with dynamic column and used that view as a normal table, then only I was able to filter with where condition as like an existing column. Hope it helps someone.

0

Hello You can Used OR Operation in collection to achieve this condition

yes, if (keep_disable = false => get all records) + (keep_disable = true, get records where sum_qty is greater than 0)

Check the below link for used of OR Operation in magento Collection

https://meetanshi.com/blog/apply-or-conditions-to-collection-in-magento-2/

1
  • Thanks Harishit, but issue was that the the quantity column was a temp column which was created run time, so we cannot use WHERE condition on it, the only way to use that column in filtering is to create a view for that and then only we can filter it as a regular column. – Gaurav Harsh Jun 20 at 5:53

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.