0

I need my getUser method to return an instance of the custom object class UserCTI. I need make two queries and map their results into the UserCTI object, or I can make a subquery within the primary query and map to UserCTI.

  • Object 1: User (Standard Object)
  • Object 3: Team (Custom Object)
  • Object 2: Team_Assignment (Custom Junction Object with Lookup relationship to User & Team)

I have already accomplished this in a different manner but I am newer to Apex and SF and have not yet used Maps and I was attempting to refactor for an existing class of mine.

global class UserCTI {
        public ID uId;
        public String uName;
        public String uProfileName;
        public String uRoleId;
        public String uRoleName;
        public String uUserName;
        public List<String> uTeams;
    }
QUERY 1:
[SELECT Id, Name, ProfileId, Profile.Name, UserRoleId, UserRole.Name, Username FROM User WHERE Id = :UserInfo.getUserId()]
QUERY 2:
[SELECT Team__r.Name from Team_Assignments__c WHERE User__r.Id = :UserInfo.getUserId()]
ATTEMPT TO SUBQUERY

global static User getUser() {
     Insert Logic
     return ....
}
1

You can do this in one query with a subquery.

SELECT Id, Name, ProfileId, Profile.Name, UserRoleId, UserRole.Name, Username,
       (SELECT Team__r.Name FROM Team_Assignments__r)
FROM User
WHERE Id = :UserInfo.getUserId()

I'm assuming that the child relationship name for the Team Assignment to User lookup is Team_Assignments; if it's not the case, you can adjust.

You can then get each property you need to populate in a UserCTI directly from the resulting User object, save the team names, which you obtain by iterating:

UserCTI myCTI = new UserCTI();
// initialize, populate, query the User record...

for (Team_Assignment__c ta : myUser.Team_Assignments__r) {
    myCTI.uTeams.add(ta.Team__r.Name);
}

You'll have to make sure that myCTI.uTeams is initialized, of course, and copy all of the other data points you want.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.