Nested Preload. How to avoid infinite recursion?

Assume 3 schemas: A, B, and C

A has_many B
B has_many C
C preloads a record of B

The scenario above causes an infinite recursion (loop) when preloading recursively under the following condition:
C_record_1 belongs_to B_record_1
C_record_2 belongs_to B_record_2
C_record_1 associates B_record_2
C_record_2 associates B_record_1

How should I efficiently restrict the condition above from happening? Can someone please provide sample code to test the logic above?

@ion Preloading does not cause infinite recursion on its own, because when you call preload you do so with a tree, and it only preloads to the depth of that tree. Can you show the code that you have which is recursing infinitely?

Per the code you DMed me, the reason it recurses infinitely is that you’re manually introducing infinite recursion.

You should consider doing something more like: A |> preload([b: :c]) |> Repo.all.

Basically the issue is that SQL modeling like you have forms a cyclic graph, and you are looking to return a tree.