Jesan Fafon
Jesan Fafon

Reputation: 2304

Sitecore: Follow relational links in Sitecore Query

I have an item structure that doens't correspond to "documents" in the standard Sitecore sense. It corresponds to data items.

One of the relationships that my items have is the following:

Person -> State -> Country

Where a Person has a link field to a State and state's have link fields to a Country.

My question is: How would one write a query to retrieve all of the People who have an eventual link to a Country of a certain abbreviation?

I'm stumped as to how to do it in Sitecore Query. My current solution is using LINQ and several queries.

Upvotes: 0

Views: 254

Answers (1)

Derek Hunziker
Derek Hunziker

Reputation: 13141

Assuming that the links between these items where created using a Reference field, such as a Droplink, Treelist, Droptree, etc., you can traverse the references/referrers using the Sitecore Links database.

Here is an example (untested) that starts with a country item and fetches any referring states. The same query is performed on the states to fetch any referring people. The results are added to a generic List<Item> collection.

List<Item> peopleList = new List<Item>();

var countryReferences = Globals.LinkDatabase.GetReferences(countryItem);
var referringStates = countryReferences.Select(c => c.GetTargetItem()).Where(c => c.Template.Key == "state");
foreach (var state in referringStates)
{
    var stateReferences = Globals.LinkDatabase.GetReferences(state);
    var referringPeople = stateReferences.Select(s => s.GetTargetItem()).Where(s => s.Template.Key == "person");
    foreach (var person in referringPeople)
    {
        peopleList.Add(person);
    }
}

Upvotes: 1

Related Questions