Skip to content

Commit bc03130

Browse files
committed
fix named Backlink to a ToOne() relation
closes #296
1 parent a96193e commit bc03130

File tree

2 files changed

+30
-8
lines changed

2 files changed

+30
-8
lines changed

generator/integration-tests/relations/lib/lib.dart

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,10 @@ class A {
77

88
String text;
99
final bs = ToMany<B>();
10+
11+
@Backlink('a2')
12+
final d2s = ToMany<D>();
13+
1014
A(this.text);
1115
}
1216

@@ -30,3 +34,16 @@ class C {
3034
String text;
3135
C(this.text);
3236
}
37+
38+
@Entity()
39+
class D {
40+
int id = 0;
41+
42+
String text;
43+
44+
final a1 = ToOne<A>();
45+
46+
final a2 = ToOne<A>();
47+
48+
D(this.text);
49+
}

generator/lib/src/code_chunks.dart

Lines changed: 13 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -490,27 +490,32 @@ class CodeChunks {
490490
ModelRelation? srcRel;
491491
ModelProperty? srcProp;
492492

493+
final throwAmbiguousError = (String prop, String rel) =>
494+
throw InvalidGenerationSourceError(
495+
'Ambiguous relation backlink source for ${entity.name}.${bl.name}.'
496+
' Matching property: $prop.'
497+
' Matching standalone relation: $rel.');
498+
493499
if (bl.srcField.isEmpty) {
494500
final matchingProps = srcEntity.properties
495501
.where((p) => p.isRelation && p.relationTarget == entity.name);
496502
final matchingRels =
497503
srcEntity.relations.where((r) => r.targetId == entity.id);
498504
final candidatesCount = matchingProps.length + matchingRels.length;
499505
if (candidatesCount > 1) {
500-
throw InvalidGenerationSourceError(
501-
'Ambiguous relation backlink source for ${entity.name}.${bl.name}.'
502-
' Matching property: $matchingProps.'
503-
' Matching standalone relations: $matchingRels.');
506+
throwAmbiguousError(matchingProps.toString(), matchingRels.toString());
504507
} else if (matchingProps.isNotEmpty) {
505508
srcProp = matchingProps.first;
506509
} else if (matchingRels.isNotEmpty) {
507510
srcRel = matchingRels.first;
508511
}
509512
} else {
510-
srcProp = srcEntity.findPropertyByName(bl.srcField);
511-
if (srcProp == null) {
512-
srcRel =
513-
srcEntity.relations.firstWhereOrNull((r) => r.name == bl.srcField);
513+
srcProp = srcEntity.findPropertyByName(bl.srcField + 'Id');
514+
srcRel =
515+
srcEntity.relations.firstWhereOrNull((r) => r.name == bl.srcField);
516+
517+
if (srcProp != null && srcRel != null) {
518+
throwAmbiguousError(srcProp.toString(), srcRel.toString());
514519
}
515520
}
516521

0 commit comments

Comments
 (0)