The code above, as I wrote in comments, will works (almost) fine if You don’t enable flat_products. Now look at this, full working method (explanations in the code):