usingSystem.Linq;usingUmbraco.Core.Composing;usingUmbraco.Core.Events;usingUmbraco.Core.Services;usingUmbraco.Core.Services.Implement;namespaceDoccers.Core.Components;publicclassRelationComponent:IComponent{privatereadonlyIRelationService _relationService;publicRelationComponent(IRelationService relationService) { _relationService = relationService; }publicvoidInitialize() {ContentService.Published+= ContentService_Published; }privatevoidContentService_Published(IContentService sender,ContentPublishedEventArgs e) { // Should never be null, to be honest.var home =sender.GetRootContent()?.FirstOrDefault();if (home ==null) return; // Get the relation type by aliasvar relationType =_relationService.GetRelationTypeByAlias("homesick");if (relationType ==null) return;foreach (var entity ine.PublishedEntities .Where(x =>x.Id!=home.Id)) { // Check if they are already relatedif (!_relationService.AreRelated(home.Id,entity.Id)) { // If not then let us relate the currenty entity to home_relationService.Relate(home.Id,entity.Id, relationType); } } }publicvoidTerminate() { //unsubscribe during shutdownContentService.Published-= ContentService_Published; }}
To have Umbraco recognize our component we need to register it in a composer:
If I know Save and Publish my Products node I get the following result:
Now let us try and fetch the data from an API.
The example below uses UmbracoApiController which is obsolete in Umbraco 14 and will be removed in Umbraco 15.
usingSystem;usingSystem.Linq;usingSystem.Net;usingSystem.Net.Http;usingSystem.Web.Http;usingUmbraco.Core.Services;usingUmbraco.Web.WebApi;namespaceDoccers.Core.Controllers.Http;publicclassRelationsController:UmbracoApiController{privatereadonlyIRelationService _relationService;publicRelationsController(IRelationService relationService) { // Alternatively you could also access // the service via the service context: // _relationService = Services.RelationService; _relationService = relationService; } [HttpGet]publicHttpResponseMessageGetByRelationTypeAlias(string alias) {var relationType =_relationService.GetRelationTypeByAlias(alias);if (relationType ==null)returnRequest.CreateResponse(HttpStatusCode.BadRequest,"Invalid relation type alias");var relations =_relationService.GetAllRelationsByRelationType(relationType.Id);var content =relations.Select(x =>Umbraco.Content(x.ChildId)) .Select(x =>newRelation() { Name =x.Name, UpdateDate =x.UpdateDate });returnRequest.CreateResponse(HttpStatusCode.OK, content); }}
Notice the x => new Relation()? We need to make sure what we are returning can be serialized. Therefore the Relation class is: