getRelation<T extends Model> method
Get a single related model.
Automatically casts a Map attribute to the related model type defined in relations. The result is cached for subsequent access.
// In Post model:
@override
Map<String, Model Function()> get relations => {'user': User.new};
User? get user => getRelation<User>('user');
// Usage:
final post = await Post.find(1);
print(post?.user?.name); // "John Doe"
Implementation
T? getRelation<T extends Model>(String key) {
final cached = _relationCache[key];
if (cached is T) return cached;
final data = _attributes[key];
if (data == null) return null;
if (data is T) return data; // Already a model, assigned rather than loaded
if (data is Map<String, dynamic>) {
final factory = relations[key];
if (factory != null) {
final model = factory() as T;
model.setRawAttributes(data, sync: true);
model.exists = true;
_relationCache[key] = model;
return model;
}
}
return null;
}