coldfusioncoldfusion-2016qoq

how to use Queryfilter function when I have to get results in terms Order by clause


I am getting error when trying to execute the below code:

myQuery = queryNew("id,name,amount","Integer,Varchar,Integer", 
            [ 
                    {id=1,name="One",amount=15}, 
                    {id=2,name="Two",amount=18}, 
                    {id=3,name="Three",amount=32},
                    {id=4,name="Four",amount=27},
                    {id=5,name="Five",amount=43},
                    {id=6,name="Six",amount=71}
            ]);

get=myQuery.filter(function(obj){
   return (order by obj.name )
});
writeOutput("The filtered query is:")
writeDump(get);

The error displays "Invalid CFML construct found on line 16 at column 22."

I know the above error is because of order by obj.name as a parameter in return. But how will I be able to do without any error? Thank you.


Solution

  • To do an order by, you're going to need to do sort() and not filter().

    <cfscript>
    myQuery = queryNew("id,name,amount","Integer,Varchar,Integer", 
                [ 
                        {id=1,name="One",amount=15}, 
                        {id=2,name="Two",amount=18}, 
                        {id=3,name="Three",amount=32},
                        {id=4,name="Four",amount=27},
                        {id=5,name="Five",amount=43},
                        {id=6,name="Six",amount=71}
                ]);
    
    myQuery.sort("name", "desc");
    writeOutput("The filtered query is:")
    writeDump(myQuery);
    </cfscript>
    

    https://trycf.com/gist/f827f61a03a173a3b13ad01a2cd13dce/lucee5?theme=monokai

    Edited: There is no need to reference get, just reference the query itself.