SwiftData Model object added to multiple parent objects moves ownership to only last parent

I thought an object could be added to as many other parents as I wanted, but now it's not behaving.

@Model
final class Genre {
	var				name:String;
	
	init(name:String) {
		self.name = name;
	}
}

@Model
final class Disc {
	var			genre:Array<Genre> = [];
}

Then elsewhere I made sure the user is not creating a duplicate Genre before adding either the existing one or a new one:

struct BlahView: View {
	@Query var		allGenres:[Genre];
	var		theseGenres; // Pretend this is actually assigned.
    
    var body: some View {
		if let idx = allGenres.firstIndex(where: { genr in
			genr.name == editStr;
		}) {
			theseGenres.append(allGenres[idx]);
		}
		else {
			theseGenres.append(Genre(name:editStr));
		}
	}
}

When the genre gets added to the 2nd parent, it goes away in the 1st parent it was added to.

I initially used the #Unique<Genre>([\.name]) thingy in Genre, but then read that it does not work when the data is stored in CloudKit, which I'm doing. Hence the check for existing I'm doing.

Answered by sjmills in 911032022

I figured it out. I'd either misunderstood what I'd read somewhere, or it was just wrong, when it said that SwiftData would figure out all the relationships when the models were so simple. So I didn't think I needed the Genre to also contain an array of all the Discs that use it. Turns out it still needs to be specified, just like with CoreData.

Accepted Answer

I figured it out. I'd either misunderstood what I'd read somewhere, or it was just wrong, when it said that SwiftData would figure out all the relationships when the models were so simple. So I didn't think I needed the Genre to also contain an array of all the Discs that use it. Turns out it still needs to be specified, just like with CoreData.