I'm encountering an issue with a one-to-many relationship between two models using SwiftData. Here's a simple example of my models:
@Model
final class TVSeries {
var title: String
@Relationship(deleteRule: .cascade, inverse: \Episode.tvSeries) var episodes: [Episode]
init(title: String, episodes: [Episode] = []) {
self.title = title
self.episodes = episodes
}
}
@Model
final class Episode {
var title: String
var tvSeries: TVSeries // <- Works fine when optional
init(title: String, tvSeries: TVSeries) {
self.title = title
self.tvSeries = tvSeries
}
}
After creating and saving a TVSeries instance with an associated Episode, fetching the TVSeries instance shows that the episodes array remains empty whereas the back-link to the TVSeries works as expected. Here's the relevant test case:
struct SwiftDataTestingTests {
@Test func testFullInit() async throws {
// Configure SwiftData context
let config = ModelConfiguration(isStoredInMemoryOnly: true)
let container = try ModelContainer(for: TVSeries.self, Episode.self, configurations: config)
let context = ModelContext(container)
context.autosaveEnabled = false
// Create entries
let tvSeries = TVSeries(title: "New Series")
let episode = Episode(title: "Episode 1", tvSeries: tvSeries)
context.insert(episode)
try context.save()
// Fetch tv series
let tvSeriesDescriptor = FetchDescriptor<TVSeries>()
let tvSeriesResult = try context.fetch(tvSeriesDescriptor)
#expect(tvSeriesResult.count == 1)
let fetchedTVSeries = try #require(tvSeriesResult.first)
#expect(fetchedTVSeries.episodes.count == 1) // <- Expectation failed: (fetchedTVSeries.episodes.count → 0) == 1
// Fetch episodes
let episodeDescriptor = FetchDescriptor<Episode>()
let episodeResult = try context.fetch(episodeDescriptor)
#expect(episodeResult.count == 1)
let fetchedEpisode = try #require(episodeResult.first)
#expect(fetchedEpisode.tvSeries.title == "New Series")
}
}
Everything seems fine when I make the tvSeries attribute in the Episode model optional, but I would prefer to leave it explicit.
I tested this on the latest XCode and XCode Beta versions running macOS Sonoma
XCode Version: 15.4 (15F31d)
XCode Beta Version: 16.0 beta 3 (16A5202i)
MacOS Version: 14.5 (23F79)
Any insights or suggestions on what might be causing this issue would be greatly appreciated. Thank you!