Add selected to relationship programmatically

984
2
09-24-2020 02:27 AM
MarkConnolly
New Contributor II

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?

Tags (1)
2 Replies
GriffinJohnson
New Contributor

I hate to ping you as I don't have an answer, but I actually have the same question and I'm hoping this will bring it around again for someone to finally answer.

0 Kudos
AlexMorris
New Contributor

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")[0]
tunnel = map_frame.listLayers("tunnel")[0]
track = map_frame.listLayers("track")[0]
rltd = map_frame.listTables("Related_Tbl")[0]

# 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.
                    if trk_feat[0].contains(tnl_feat[0]):
                        mm_tbl.insertRow((tnl_tbl[1], trk_tbl[1], trk_tbl[2]))

0 Kudos