0

I want to get id of product selected on opportunity record. There is lookup relationship between Opportunity and product. All I want is id of the product selected by user on that record. below is my code.

    public without sharing class Test {

    public static void Org (List<Opportunity> organisations){
   Set<Id> OrgIds = new Set<Id>();


 for(Opportunity o : organisations){

            OrgIds.add(o.Id);
        }

 for( Product__c product : [SELECT ID, Name, Product_ID__c FROM Product__c WHERE ID IN :OrgIds])
        {
        system.debug('I am in here' + product.ID );
       }

}
}

Product__C is a Custom object

Added lookup between opportunity and product object.

2 Answers 2

2

If the lookup field is on the Opportunity then you would need to query the opportunity object not the Product__c object. I'm guessing something like this:

public without sharing class Test {

  public static void Org (List<Opportunity> organisations){
    Set<Id> prodIds = new Set<Id>();

    for(Opportunity o : organisations) {
      prodIds.add(o.product__c);
    }

    for( Product__c product : [SELECT ID, Name, Product_ID__c FROM Product__c WHERE ID IN :prodIds])
    {
      system.debug('I am in here' + product.Product_ID__c );
    }

  }
}
10
  • but if I query on opportunity how would I get Id of product? As product is lookup on opportunity I have tried doing Product__r.Product_ID__c but that also gives error. Loop variable must be Sobject or list of opportuity.
    – Ricky
    Oct 7, 2015 at 19:27
  • @Ricky Product_ID__c is the ID of the product. The relationship field holds the ID of the related object.
    – Jenny B
    Oct 7, 2015 at 19:29
  • So do you mean I can simply query product__c lookup field on opportunity ? that will give me id of that as well?
    – Ricky
    Oct 7, 2015 at 19:31
  • @Ricky yup, that is correct!
    – Jenny B
    Oct 7, 2015 at 19:32
  • ok I am still confused here. Let me write query here again [SELECT ID,Name, Product__c from Opportunity where Product__c IN : OrgIds] is this correct?
    – Ricky
    Oct 7, 2015 at 19:35
0

The Ids that you're gathering in the for loop before the query are for Opportunities, not Product__c.

Your query should be on Opportunity, not on Product__c.

1
  • but how would I be able to get product_ID__C from product if I query opportunity?
    – Ricky
    Oct 7, 2015 at 19:30

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .