Skip to content
This repository was archived by the owner on Jun 3, 2024. It is now read-only.

Filtering Queries

Jonathan Gillespie edited this page May 30, 2017 · 4 revisions

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. The type of filter is determined based on which QueryFilter constructor you use

Basic Filter: Create a Method to Return Converted Leads for the Current User

Scenario: You have a lead repository (LeadRepository.cls) and you want to create a method that returns leads that have been converted and that are owned by the current user. In SOQL, it would be

SELECT Id FROM Lead 
WHERE OwnerId = :UserInfo.getUserId()
AND IsConverted = true

QueryFilter Constructor to Use

public QueryFilter(Schema.SObjectField fieldToFilter, QueryOperator operator, Object value)

Creating Your Method with QueryFilter

public with sharing class LeadRepository extends SObjectRepository {
    
    public LeadRepository() {
        super(Schema.Lead.SObjectType);
    }

    public List<Lead> getMyConvertedLeads() {
        return (List<Lead>)this.Query
            // Only include leads owned by the current user
            .filterBy(new QueryFilter(Schema.Lead.OwnerId, QueryOperator.EQUALS, UserInfo.getUserId()))
            // Only include leads that have been converted
            .filterBy(new QueryFilter(Schema.Lead.IsConverted, QueryOperator.EQUALS, true))
            .getQueryResults();
    }

}

Parent filter

Scenario: You have a lead repository (LeadRepository.cls) and you want to create a method that returns leads that were created by inactive users. In SOQL, it would be

SELECT Id FROM Lead 
WHERE CreatedBy.IsActive = false

QueryFilter Constructor to Use

public QueryFilter(Schema.SObjectField parentRelationshipField, Schema.SObjectField fieldToFilter, QueryOperator operator, Object value)

Creating Your Method with QueryFilter

public with sharing class LeadRepository extends SObjectRepository {
    
    public LeadRepository() {
        super(Schema.Lead.SObjectType);
    }

    public List<Lead> getMyConvertedLeads() {
        return (List<Lead>)this.Query
            // Only include leads owned by the current user
            .filterBy(new QueryFilter(Schema.Lead.OwnerId, QueryOperator.EQUALS, UserInfo.getUserId()))
            // Only include leads that have been converted
            .filterBy(new QueryFilter(Schema.Lead.IsConverted, QueryOperator.EQUALS, true))
            .getQueryResults();
    }

}

Grandparent filter

    public QueryFilter(List<Schema.SObjectField> sortedParentRelationshipFields, Schema.SObjectField fieldToFilter, QueryOperator operator, Object value) {
Clone this wiki locally