salesforceapexsoql

How do i query contacts conditioned by user license?


I trying to write some dummy apex code which can list me all contacts whos ownerid belong to a user have specific licenses. I've so far been to able to extract them seperately, I am not able to do in one query though.

List<User> communityUsers = [Select Id, name From User Where Profile.UserLicense.LicenseDefinitionKey = 'PID_Customer_Community' OR Profile.UserLicense.LicenseDefinitionKey = 'PID_Customer_Community_Login'];
List<Contact> contacts = [select id, name, ownerid from Contact where ownerid in :communityUsers];

I want to check the account of the contact, and see whether it has any contact point address, and whether any those which is available is set as default?


Solution

  • You can merge your queries pretty straightforward, you can go "up" with dot notation up to 5 times.

    SELECT Id, Name, OwnerId
    FROM Contact
    WHERE Owner.Profile.UserLicense.LicenseDefinitionKey IN ('PID_Customer_Community', 'PID_Customer_Community_Login')
    

    or if you prefer this format

    SELECT Id, Name, OwnerId
    FROM Contact
    WHERE OwnerId IN (SELECT Id FROM User WHERE Profile.UserLicense.LicenseDefinitionKey IN ('PID_Customer_Community', 'PID_Customer_Community_Login'))
    

    I haven't worked with contact points and don't have good sample data. Check if this compiles?

    select id, name, 
        (select Id, IsDefault from ContactPointAddresses)
    from account
    where Id IN (select accountid from contact WHERE Owner.Profile.UserLicense.LicenseDefinitionKey IN ('PID_Customer_Community', 'PID_Customer_Community_Login'))