Skip to main content

Get Relationships Between Models

To get the relationship for a specified field name, use the GetRelation method of the IModel object. To get a related collection, use the GetRelations method of the IModel object. You can specify either an owned or referenced field name.

public void GetRelation(ICommandContext c, ICommandParams p) 
{
//Get the currently displayed model
IModel model = c.App.Workspace.CurrentModel;

//Specify the field name
var fieldName = "FieldSomeName";

//Get the relationship
IRelationship relationship = model.GetRelation(fieldName);
c.App.Workspace.Output.WriteLine("sample", $"Relationship-Class: {relationship.Metaclass.Name}");

//To get multiple relationships, use IModel.GetRelations
var fieldsName = "FieldsSomeName";
IRelationshipCollection relationships = model.GetRelations(fieldsName);
foreach(var r in relationships)
{
c.App.Workspace.Output.WriteLine("sample", $"Relationship-Class: {r.Metaclass.Name}");
c.App.Workspace.Output.WriteLine("sample", $" Relationship-Source: {r.Source.Name}");
c.App.Workspace.Output.WriteLine("sample", $" Relationship-Target: {r.Target.Name}");
}
}

If you want to specify a model and get the relationships, use the GetRelationsOf method of the IModel object. This will get all relationships, regardless of whether they are owned or referenced.

public void GetRelationsOf(ICommandContext c, ICommandParams p) 
{
//Get the currently displayed model
IModel model = c.App.Workspace.CurrentModel;

//Specify the model related to the displayed model
IModel targetModel = c.App.Workspace.CurrentProject.GetModelByPath("SomeModelPath");

//Get the relationships between models
IRelationshipCollection relationships = model.GetRelationsOf(targetModel);
foreach(var relationship in relationships)
{
c.App.Workspace.Output.WriteLine("sample", $"Relationship-Class: {relationship.Metaclass.Name}");
}
}