[SalesForce] Error: Compile Error: Invalid foreign key relationship: Opportunity.StageName at line 6 column 13

trigger UpdateLease on Opportunity ( After update) {

   List<ID> OppIds = New List<ID>();

    for (opportunity opp : trigger.new) {
        if (opp.StageName.equalsIgnoreCase = 'Closed won') {
            OppIds.add(opp.Id);   
        }
   }
        if(!OppIds.isEmpty()){
        List<Product2> products = [Select id from Product2 where Opportunity /*Lookup Field*/ in : oppIds];

        for(Product2 prod : products){
        prod.Available_for_lease =true;
        }
        update products;
}
}

I am new to apex please help. I am creating a trigger that will update the checkbox in the products if the opportunity stage was set to "closed won".

Best Answer

There's no direct link between products and opportunities. You need to query OpportunityLineItem to get the products:

Opportunity[] wonOpps = new Opportunity[0];
for(Opportunity record: Trigger.new) {
    if(record.StageName == 'closed won') {
        wonOpps.add(record);
    }
}
if(wonOpps.isEmpty()) {
    return;
}
Product2[] products = [SELECT Id FROM Product2 WHERE Id IN (SELECT Product2Id FROM OpportunitLineItem WHERE OpportunityId IN :wonOpps)];
for(Product2 product: products) {
     product.Available_for_Lease__c = true;
}
update products;

I think you might be doing this wrong though... a product is a generic item (e.g. a Snickers candy bar), not a specific item (e.g. the Snickers candy bar). You might want to build a way to associate assets with opportunities, because that's what assets are meant to be used for.

Related Topic