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
Carolina W 2Carolina W 2 

How to refactor these queries in only one?

I have to transform this method using another method of type Selector. Is it possible to make only one query in this case, respecting each criterion or will I have to create 4 selector's methods? I'm asking this because in each query the != is in a different position.

public static List<Product2> getProduct(String color, String brand,  String model){
        
        if (brand == null || brand == ''){
            return [SELECT Color__c, Name,Id, Photo__c, ProductCode FROM Product2 WHERE Brand__c != null AND Model__c != null AND Color__c != null];
        }else{
            if (model == null || model == ''){
                return [SELECT Color__c,Name,Id, Photo__c, ProductCode FROM Product2 WHERE Brand__c = :brand AND Model__c != null AND Color__c != null];
            } else{
                if (color == null || color == ''){
                    return [SELECT Color__c,Name,Id, Photo__c, ProductCode FROM Product2 WHERE Brand__c = :brand AND Model__c = :model AND Color__c != null];
                } else{
                    return [SELECT Color__c,Name,Id, Photo__c, ProductCode FROM Product2 WHERE Brand__c = :brand AND Model__c = :model AND Color__c = :color];    
                }
            }
        }
    }