Relation Service
The RelationService allows creating relations between objects that would otherwise have no obvious connection.
The following examples demonstrate how to use RelationService.
Automatically relate to the root node
To perform this task, implement a Notification Handler:
Read more about composing Umbraco here.
using Umbraco.Cms.Core.Events;
using Umbraco.Cms.Core.Notifications;
using Umbraco.Cms.Core.Services;
namespace Doccers.Core.Components;
public class ContentPublishedNotificationHandler(IContentService contentService, IRelationService relationService) : INotificationHandler<ContentPublishedNotification>
{
public void Handle(ContentPublishedNotification notification)
{
var home = contentService.GetRootContent().FirstOrDefault();
if (home == null) return;
// Get the relation type by alias
var relationType = relationService.GetRelationTypeByAlias("homesick");
if (relationType == null) return;
foreach (var entity in notification.PublishedEntities
.Where(x => x.Id != home.Id))
{
// Check if they are already related
if (!relationService.AreRelated(home.Id, entity.Id))
{
// If not then let us relate the current entity to home
relationService.Relate(home.Id, entity.Id, relationType);
}
}
}
}To make Umbraco recognize the Notification Handler, register it in a composer:
After saving and publishing the Products node, the following result is displayed:
The next step is to fetch the data from an API.
Note the x => new Relation() expression. The returned data must be serializable, therefore the Relation class is defined as follows:
Browsing /umbraco/api/relations/getbyrelationtypealias?alias=homesick returns the following output:
Last updated
Was this helpful?