Aashish Katta
Aashish Katta

Reputation: 1214

Using drools for multiple object of same type and having relationships

Hey I have a following problem to solve using drools-

We have an Object-

Class Product{
 String name;
 double cost;
 double margin;
 double sellPrice;
}

We have a Product object-P1 and it can have multiple parents/relations of type Product lets say P1, P2, P3.... so on

Now the rule has to be like-

rule when: P1.cost<100
rule then: P1.sellPrice=P2.sellPrice+P3.sellPrice+.....

I am trying figure out a way/design to achieve this.

Upvotes: 0

Views: 2627

Answers (1)

antmendoza
antmendoza

Reputation: 401

I thing you can use the keyword collect, it allow you reason over collection from the given source, in this case every Product inserted in the working memory (less product who is being evaluated )

I hope this piece of code can guide you:

    rule "Sum sellPrice's property Product if Product's cost < 100"
    no-loop
        when
            $p : Product(cost<100) 
            $items : java.util.List(size > 0) //execute rule if list.size > 0
                    from collect( Product(name != $p.name) )    //create list from each Product less this ($p)  
        then
            double totalSellPrice = 0;
            Product p = null;
            for(Object item: $items)
            {
                p = (Product)item;
                totalSellPrice += p.getSellPrice();
            }
            //finally modify product who is being evaluated
            modify($p){setSellPrice(totalSellPrice)};
    end

This post explain who collect (from and accumulate) works http://blog.athico.com/2007/06/chained-from-accumulate-collect.html

Upvotes: 1

Related Questions