SwiftData Many-To-Many relationship not working

Hi guys, I have an issue with many-to-many relationships in SwiftData. Even though the order of actions is correct; I fist create the objects with their non optional array initialized empty in their own init-method’s parameter and then insert the models in the model context. For example:

  1. Create model A
  2. Insert model A
  3. Create model B
  4. Insert model B

And then I try to establish their relationships by modifying model A’s array, however model B’s array doesn’t update correctly and gives wrong results. How can I fix this?

If needed, I can for sure provide some code but since the code of these actions is all over the project, I thought it would be easier to first try and explain it simply like this. Thanks for any expertise or opinions! Have a great day!

Update: The problem seems to be in the predicate that I use to fetch all model B’s related to Model A, where model B is a Criterion and A a Subgoal. This is my code:

extension Subgoal {
    /// The fetch descriptor to fetch all criteria related to this subgoal.
    func criteriaDescriptor() -> FetchDescriptor<Criterion> {
        let subgoalId = self.persistentModelID
        let predicate = #Predicate<Criterion> { criterion in
            criterion.subgoals.contains {
                $0.persistentModelID == subgoalId
            }
        }
        return FetchDescriptor<Criterion>(predicate: predicate)
    }
}

I don’t know what’s wrong with my code, does anyone know why this descriptor might return the wrong results?