function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Reddy@SFDCReddy@SFDC 

How can query with two standard objects

Hi All,

   Actually i want to query on Account and User .....where account.ownerid==user.id  how can i?

SrikanthKuruvaSrikanthKuruva

you want to query accounts where the owner is a single user (logged in user) or multiple users?

if it is a single user i.e. logged in user then you can do

[select field1, field2 from account where ownerid = :userinfo.getUserid()]

if it is multiple users you need to do the following

 

List<Id> usrids = new list<id>();
for(user u : [select id from user where <your condition>])
{
usrids.add(u.id);
}
List<Account> acc = [select id from Account where ownerid in :usrids];

 

sfcksfck

Here's another interpretation of the question. The following code gives you a map of account objects paired up with the user objects that own them. Of course instead of Phone and FirstName / LastName you could choose whatever fields need  to be available in the objects you retrieve.

 

list<account> accs = [select Phone, ownerid from account];
list<user> owners = [select FirstName from user];
map<account, user> result = new map<account, user>{};
for ( account acc : accs )
{
	for ( user ownr : owners )
	{
		if ( acc.ownerid == ownr.id )
		{
			result.put( acc, ownr );
			break;
		}
	}
}
system.debug(result);

 

 

vishal@forcevishal@force

but it's not a good practice to have a for loop within a for loop considering the governor limits.  

sfcksfck

vishal@force wrote:

but it's not a good practice to have a for loop within a for loop considering the governor limits.  

Can you retrieve account instances and user instances and pair them up without using nested loops? 

aebenaeben

Here is another way.

 

Map<Id, User> usersMap = new Map<Id, User>([select Id from User where <Your Conditions>]);

List<Account> accounts = [select Id from Account where OwnerId in :usersMap.keySet()];

 

 

vishal@forcevishal@force

sfck : Hi, my point was in general terms. For the above requirement, I agree we will need to have a for within a for since there is no relation between the objects. 

I added that point so as to tell him that this needs to be done only when there is no other way. :)