SOQL query with Map keyeset

I need help in correcting this code.newbie to apex.I want to remove sessions with matching session_id__c from TrainSessions.I have written code like this

map<String, GED__c> NonGEDs= new map<string, GED__c>([SELECT  Session_Id__c FROM GED__c WHERE  User_Id__c = :userid AND Device__c = 'N']);

TrainSession[] removesessions = [SELECT Id FROM TrainSession WHERE ParentId = NULL and SessionType != 'GA' and UsersId = :userid  and  Id in :NonGEDs.keyset() ORDER BY CreatedDate DESC];

First query session_id__c is Text field map key datatype is string. but i need to use that against id field in second query as part of IN clause. How can I do it? Thanks for help.

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

There’s no way to automatically populate a map of SObject records as you’re trying to do in the first line.

However, assuming Session_Id__c contains only null values and legal Id values (either 15 or 18 characters), you can make a map of AggregateResult values to automatically convert the field to Id values:

Map<Id, AggregateResult> NonGEDS = new Map<Id, AggregateResult>(
    [SELECT Session_Id__c Id
     FROM GED__c
     WHERE User_Id__c = :userId AND Device__c = 'N'
     GROUP BY Session_Id__c]);

TrainSession__c[] removesessions = 
    [SELECT Id FROM TrainSession__c 
     WHERE  ParentId__c = NULL AND 
            SessionType__c != 'GA' AND 
            User_Id__c = :userid AND
            Id in :NonGEDs.keyset()
     ORDER BY CreatedDate DESC];

Note that the grouped field must be aliased to the literal field value Id in order for the map to work correctly.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x