-
Notifications
You must be signed in to change notification settings - Fork 15
Filtering Queries
Queries generated by SObject repositories can be filtered by creating instances of QueryFilter.cls - any query filters provided are used to generate the 'WHERE' clause in the dynamic SOQL & SOSL queries.
Nebula can filter queries at 3 levels, based on which QueryFilter constructor you use.
Scenario: You have a lead repository (LeadRepository.cls) and you want to create a method that returns accounts owned by the current user. In SOQL, it would be
SELECT Id FROM Account
WHERE OwnerId = :UserInfo.getUserId()
public QueryFilter(Schema.SObjectField fieldToFilter, QueryOperator operator, Object value)
public with sharing class AccountRepository extends SObjectRepository {
public AccountRepository() {
super(Schema.Account.SObjectType);
}
public List<Account> getMyAccounts() {
return (List<Lead>)this.Query
// Only include accounts owned by the current user
.filterBy(new QueryFilter(Schema.Account.OwnerId, QueryOperator.EQUALS, UserInfo.getUserId()))
.getQueryResults();
}
}
Scenario: You have an account repository (AccountRepository.cls) and you want to create a method that returns accounts that are owned by inactive users. In SOQL, it would be
SELECT Id FROM Account
WHERE Owner.IsActive = false
public QueryFilter(Schema.SObjectField parentRelationshipField, Schema.SObjectField fieldToFilter, QueryOperator operator, Object value)
public with sharing class AccountRepository extends SObjectRepository {
public AccountRepository() {
super(Schema.Account.SObjectType);
}
public List<Account> getAccountsWithInactiveOwners() {
return (List<Account>)this.Query
// Only include accounts owned by users with a certain profile
.filterBy(new QueryFilter(Schema.Account.OwnerId, Schema.User.IsActive, QueryOperator.EQUALS, false))
.getQueryResults();
}
}
Scenario: You have an account repository (AccountRepository.cls) and you want to create a method that returns accounts owned by users with a certain profile called 'MyCustomProfile'. In SOQL, it would be
SELECT Id FROM Account
WHERE Owner.Profile.Name = 'MyCustomProfile'
public QueryFilter(List<Schema.SObjectField> sortedParentRelationshipFields, Schema.SObjectField fieldToFilter, QueryOperator operator, Object value)
public with sharing class AccountRepository extends SObjectRepository {
public AccountRepository() {
super(Schema.Account.SObjectType);
}
public List<Account> getAccountsOwnedByMyCustomProfile() {
// Nebula uses your provided list of fields to build the relationships between the objects
List<Schema.SObjectField> grandparentFields = new List<Schema.SObjectField>{
Schema.Account.OwnerId, Schema.User.ProfileId
};
return (List<Account>)this.Query
// Only include accounts owned by users with a certain profile
.filterBy(new QueryFilter(grandparentFields, Schema.Profile.Name, QueryOperator.EQUALS, 'MyCustomProfile'))
.getQueryResults();
}
}