Question

Getting my feet wet on CAML. I was able to get a query that shows a count for a list. Now I need to do count based on multiple information.

Dog
Dog
Cat
Cat
Cat
fish
fish
fish
fish

Loops through and creates the following:

Dog: 2
Cat: 3
Fish: 4

So how would the Query look look? I'm thinking the below but this looks too cumbersome and repetative. Is there an easier way to have multiple WHERE clauses?

var dog = "<View><Query><Where><Eq><FieldRef Name='Pet' /><Value Type='Text'>Dog</Value></Eq></Where></Query><RowLimit>0</RowLimit></View>";
var cat = "<View><Query><Where><Eq><FieldRef Name='Pet' /><Value Type='Text'>Cat</Value></Eq></Where></Query><RowLimit>0</RowLimit></View>";
var fish= "<View><Query><Where><Eq><FieldRef Name='Pet' /><Value Type='Text'>fish</Value></Eq></Where></Query><RowLimit>0</RowLimit></View>";
Était-ce utile?

La solution

You can't have multiple WHERE clauses in a single query, but there's nothing wrong with doing multiple queries sequentially.

If I understand correctly, your code works as expected but you want to reduce the repetitiveness of having three long query strings that are basically identical.

In that case, the solution is to create an array of keywords and map it to a function that produces the query strings.

var keywords = ["Dog", "Cat", "Fish"];

var makeQueryString = function (keyword) {
    return ["<View><Query><Where><Eq><FieldRef Name='Pet' /><Value Type='Text'>",
        keyword,
        "</Value></Eq></Where></Query><RowLimit>0</RowLimit></View>"
    ].join('')
}

keywords.map(makeQueryString);

// Results:
// [ '<View><Query><Where><Eq><FieldRef Name=\'Pet\' /><Value Type=\'Text\'>Dog</Value></Eq></Where></Query><RowLimit>0</RowLimit></View>',
//   '<View><Query><Where><Eq><FieldRef Name=\'Pet\' /><Value Type=\'Text\'>Cat</Value></Eq></Where></Query><RowLimit>0</RowLimit></View>',
//   '<View><Query><Where><Eq><FieldRef Name=\'Pet\' /><Value Type=\'Text\'>Fish</Value></Eq></Where></Query><RowLimit>0</RowLimit></View>' ]

From there you can use .map() again to actually invoke each query and handle the results, but that is outside the scope of this answer.

Licencié sous: CC-BY-SA avec attribution
Non affilié à sharepoint.stackexchange
scroll top