按特定用户的区域获取帐户

时间:2013-07-19 22:17:15

标签: salesforce apex-code

我一直在审核区域管理ERD,并试图了解如何按分配给特定用户的区域查询帐户。

在我的控制器中,我正在使用UserInfo.getUserId()来获取当前用户的userId。

我需要获取该用户按地区过滤的帐户列表。

查看ERD,看起来我需要查询组表,但组表上的ID与userId没有任何匹配,因此如何获取特定用户的相关组ID ?如何获取特定用户的一组ID,这些ID可用于在accountShare表上进行查询,然后该表将返回该用户按区域划分的帐户ID列表?

我是否正确穿过了物体?我错过了某处的关系。

感谢您的帮助。

3 个答案:

答案 0 :(得分:2)

代码看起来像这样

1)

Map<Id,UserTerritory> UserTerritoryCurrentUserMap = new  Map<Id,UserTerritory>([Select u.UserId, u.TerritoryId, u.IsActive, u.Id  From UserTerritory u Where u.isActive=true and u.userId =: userId]);

2)

set<Id> TerritoryIdSet = new set<Id>();
for (UserTerritory ut:UserTerritoryCurrentUserMap.values()) {
    TerritoryIdSet.add(ut.TerritoryId);
}

3)

list<Group> map_group = [Select Id, RelatedId from Group where Type='Territory' AND RelatedId IN : TerritoryIdSet];

4)

List<AccountShare> lst_AccountShare = [Select Id, UserOrGroupId, AccountId from AccountShare where ( UserOrGroupId IN : map_group OR  UserOrGroupId =:userId )AND RowCause IN ('Territory', 'TerritoryManual', 'TerritoryRule')];

答案 1 :(得分:1)

从冬季15开始,您可以使用新的“使用范围”子句来过滤用户指定区域中的记录,前提是您的类使用sharing /作为当前用户运行此查询。那就是,

  

SELECT Id,Name FROM Account US SCOPE My_Territory

将返回正在运行的用户所在区域中的所有帐户。这也应该返回子区域中的帐户。

在这里帮助文章, https://help.salesforce.com/apex/HTViewSolution?id=000204543&language=en_US

答案 2 :(得分:0)

@MnZ

以上代码在儿童区域的支持下得到扩展。通过更改 noOfLevels 变量来决定它应该支持多少级别。我希望你们中的一些人会发现它很有用。

&#13;
&#13;
Integer noOfLevels = 3;
Map<Id, UserTerritory> mIdTer = new Map<Id, UserTerritory>([Select UserId, TerritoryId, SystemModstamp, LastModifiedDate, LastModifiedById, IsActive, Id From UserTerritory where  UserId = :userId]);

set<Id> TerritoryIdSet = new set<Id>();
for(UserTerritory ut:mIdTer.values()){
  TerritoryIdSet.add(ut.TerritoryId);
}

Territory[] nTers = new Territory[]{};
set<Id> parentIds = new Set<Id>();
parentIds.addAll(TerritoryIdSet);
for(integer i = 0 ; i < noOfLevels; i++){
	nTers = [select Id from Territory where ParentTerritoryId in :parentIds];
	if(nTers.size() > 0){
		parentIds = new Set<Id>();
		for(Territory t1 : nTers){
			TerritoryIdSet.add(t1.Id);
			parentIds.add(t1.Id);
		}
	} else {
		break;
	}
}


list<Group> map_group = [Select Id, RelatedId from Group where Type='Territory' AND RelatedId IN : TerritoryIdSet];

List<AccountShare> lst_AccountShare = [Select Id, UserOrGroupId, AccountId from AccountShare where ( UserOrGroupId IN : map_group OR  UserOrGroupId =:userId )AND RowCause IN ('Territory', 'TerritoryManual', 'TerritoryRule')];

Map<Id, Account> mId2acc = new Map<Id,Account>();

for(AccountShare a1 : lst_AccountShare){
	mId2acc.put(a1.AccountId, null);
}

mId2acc = new Map<Id, Account>([select Id, Target_Call__c  from Account where Id in: mId2acc.keySet()]);
&#13;
&#13;
&#13;