Model Many to Many relationships

If I have a many-to-many set of relationships that I want to model, what are performant and pleasant ways to do this?

E.g. As can have many Bs, and different As have a relationship with the same B:


struct A
    contents
end

struct B
    val
end


a1 = A([])
a2 = A([])

b1 = B(42)

push!(a1.contents,b1)
push!(a2.contents,b1)

b1 = B(50)

a1.contents # still B(42)

I’d like to be able to manipulate b1 and have a1 and a2 both reflect the change. Are there patterns/techniques to accommodate this?

1 Like

The variable b1 is rebound to a newly created B(50) in your code, but a1 and a2 do not update because they keep the (previously bound) value of b1, not the variable itself. Off the top of my head an easy way to achieve what you want is with mutable struct, but there might be performance caveats.

struct A
    contents
end

mutable struct B
    val
end

a1 = A([])
a2 = A([])

b1 = B(42)

push!(a1.contents,b1)
push!(a2.contents,b1)

b1.val = 50
2 Likes

Perhaps you want to have each object just be itself, and then create a graph that represents the relationships among all of them?

3 Likes

From 2020 juliacon:

2 Likes