0

I have a hierachrical field on user object, I want to fetch the value inside apex to send mails. but i am getting:

SObject row was retrieved via SOQL without querying the requested field

User u = [select id, Email, Name from user LIMIT 10];
User u1 =[select id, Name, Manager__r.id from user where Id  =:u.Manager__r.id];
Messaging.MassEmailMessage mail = new Messaging.MassEmailMessage();
List<String> sendTo = new List<String>();
sendTo.add(u.Id);
sendTo.add(u1.Manager__r.Id);

The soql query works in developer console but not in apex. How can I fetch in apex?

2 Answers 2

0

You did not query the Managerid in your first SOQL, hence the error.

Replace the following

User u = [select id, Email, Name from user LIMIT 10];

With this

User u = [select id, Email, Manager__c Name from user LIMIT 10];

Efficiency check

On the efficiency grounds, you have not fully mentioned your requirements, but you could use something like the code given below to make your stuff more readable and better:

User userwithManger = [select id, Email, Name, Manager__c from user LIMIT 10];
// You dont need to use the following soql. User with his/her manager id could be retrieved using single soql. more effcient.
// User u1 =[select id, Name, Manager__r.id from user where Id  =:u.Manager__r.id];
Messaging.MassEmailMessage mail = new Messaging.MassEmailMessage();
List<String> sendTo = new List<String>();
sendTo.add(userwithManger.Id);  // id of the user
sendTo.add(userwithManger.Manager__c); // id of the manager

P.S. I don't understand why are you adding Id to the sendTo list, I think it should have been email but may be you have some other requirement. Secondly, Manager is out-of-the-box standard User field. Manager__r means you have implemented a custom field. So the above solution is as per your requirement mentioned in the question.

2
  • Thanks for the answer..wat im trying to do is to send emails to user based on the user hierachry... 1)sql query User u = [select id, Email, Name from user ] 2) User u1 =[select id, Name, Manager__r.id from user where Id =:u.id]; Basically i am fetching the user manager in the second sql and then am sending the email alert... it goes upto 4 levels...... like CEO/VP.... I have a custom field on User which is hierachry
    – Kiran
    Commented Mar 9, 2017 at 13:06
  • So the CEO/VP has no manager assigned to them? If I ask-business wise, how do you identify that a particular user is the Bill Gates? :)
    – Mahmood
    Commented Mar 9, 2017 at 13:20
0

You need to query Manager__r field in the first query. User u = [select id, Manager__r.Id, Email, Name from user LIMIT 10];

You must log in to answer this question.

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