+ Start a Discussion
Craig JonesCraig Jones 

Getting data from subquery on junction object



Im struggling at getting some data from an query i run.


My set up is:


Product__c: name, description


JuncProdToAccount: Product__c, Account (these two links are master-detail relationships)


Account (standard salesforce account object)


And i run the query below:


Select Id, Name (Select Account__r.Name from JuncProdToAccount__r) from Product


I was then hoping to display the Product Name and the Account Names it is linked to in a visualforce page... but i am really struggling at getting the Account.Name out of the query.



I want to show for Example:


Product1 : Account1, Account2

Product2 : Account1

Product3 : Account2, Account 3


Thanks for any help!

Best Answer chosen by Admin (Salesforce Developers) 
Craig JonesCraig Jones

I figured this out... so thought i would give my solution for those who care :)



Prodserv__c[] products = (List<Prodserv__c>) [SELECT Name, Description__c,(SELECT Account__r.Name FROM JuncServiceToAccounts1__r) FROM Prodserv__c];
for(Prodserv__c product: products) {
    List<JuncServiceToAccount__c> accounts = (List<JuncServiceToAccount__c>)product.getSObjects('JuncServiceToAccounts1__r');
    if(accounts!=null) {
        for(JuncServiceToAccount__c servAcc: accounts) {
            Account account = (Account) servAcc.getSObject('Account__r');