Say I have (1) a polygon feature layer and (2) a point feature layer and a relationship class between the two. The points that lie in each polygon are related to that polygon.
For existing features, the standard way of creating the relationship is to select the polygon and points, right-click on the layer in the attributes pane and select "Add selected to relationship".
Is there a way to do this programatically? For example in Arcpy? Maybe using a point in polygon selection/query followed by something else?
There doesnt seem to be a way to add selected features to the relationship without having to physically click buttons which is time consuming and inefficient. The only way I can think to do it would be to run a point-in-polygon selection/query for each polygon, get the polygon key and then update the key for each feature in the points layer. Not very elegant but is this the only way?
If you insert GlobalID's of related features directly into the relationship table, with message direction "Both directions" on creation of relationship class then you can insert the Global ID as Foreign Key directly and this will create the relationship.
I did for a M:N relationship in the related table. Script Example below:
aprx = arcpy.mp.ArcGISProject("CURRENT")
map_frame = aprx.listMaps("Map")
tunnel = map_frame.listLayers("tunnel")
track = map_frame.listLayers("track")
rltd = map_frame.listTables("Related_Tbl")
# M:N Table as tunnel can contain multiple tracks, and tracks travel through many #tunnels segments.
mm_tbl = arcpy.da.InsertCursor(rltd, ["Tunnel_ID", "Track_ID", "Type"])
with arcpy.da.SearchCursor(track, ["SHAPE@", "GlobalID", "type"]) as trk_tbl:
for trk_feat in trk_tbl:
with arcpy.da.SearchCursor(duct, ["SHAPE@", "GlobalID"]) as tnl_tbl:
for tnl_feat in tnl_tbl:
# In this case Track is continous and Tunnel is segmented, so Track contains Tunnel #only for spatial relation.
mm_tbl.insertRow((tnl_tbl, trk_tbl, trk_tbl))