aws-amplify / aws-amplify/amplify-codegen

Generated Dart model drops foreign key field in belongsTo relationship (Gen 2)

Open
#1,034 2 comments 0 reactions 0 assignees View on GitHub
Dominant language
TypeScript
Stars
59
Forks
64
PR merge metrics
No merged PRs in 30d

Description

I'm using Gen 2 and running into an issue where `modelgen` strips out an explicitly defined foreign key field from the generated Flutter class.

I have a 1-to-many relationship where a Device may belong to multiple Sites. I explicitly defined `deviceId: a.string()` on `Site` because I need to use it as a secondary index (`listSitesByDevice`).

However, the generated `Site.dart` only includes the `Device` relationship object and completely removes the `deviceId` string field.

**Schema (`resource.ts`):**
```ts
Device: a.model({
id: a.id().required(),
pin: a.string(),
sites: a.hasMany('Site', 'deviceId'),
})

Site: a.model({
id: a.id().required(),
name: a.string(),
deviceId: a.string(), // Explicitly defined here
device: a.belongsTo('Device', 'deviceId'),
})
.secondaryIndexes(index => [
index('deviceId').queryField('listSitesByDevice')
])
```

**Generated Dart code (`Site.dart`):**
```dart
class Site extends amplify_core.Model {
static const classType = const _SiteModelType();
final String id;
final String? _name;
final Device? _device; // Relationship object is here
final amplify_core.TemporalDateTime? _createdAt;
final amplify_core.TemporalDateTime? _updatedAt;

// Missing _deviceId field!

```

**Generation commands used:**
```bash
npx ampx generate outputs --format dart --out-dir lib --profile $(AWS_PROFILE_NAME) --app-id $(APP_ID) --branch $(BRANCH_NAME)

npx ampx generate graphql-client-code --format modelgen --model-target dart --out lib/models --profile $(AWS_PROFILE_NAME) --app-id $(APP_ID) --branch $(BRANCH_NAME)
```

Is there a way to force `modelgen` to keep the `deviceId` field in the Dart class, **without having to write nested graphql queries**? I need the `deviceId` to easily query the secondary index.

Thank you very much.

Contributor guide

Open the contributing guide

Research direction

Start with the resource.ts schema and the Dart model-generation path exercised by the two listed npx ampx commands. Reproduce the issue and inspect the generated lib/models/Site.dart output, focusing on how the explicit deviceId and belongsTo relationship are represented. Done means the generated model retains deviceId while still supporting the Device relationship and secondary-index query.

Written by the indexing model from the issue text.

Assessment

Tech stack
dart, flutter, typescript
Domain
mobile, tooling
Issue type
Bug
Difficulty
3/5
Estimated time
1-2 days
Activity status
Quiet
Clarity
Mostly clear
Newbie friendliness
55/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.