Looking for how to use this in your app?See Frontend Libraries →
データモデル識別子のカスタマイズ
識別子はモデル定義の .identifier() メソッドを使用して定義されます。.identifier() メソッドの使用はオプションです。存在しない場合、モデルは ID 型の id というフィールドを自動的に持ち、手動で指定しない限り自動生成されます。
const schema = a.schema({ Todo: a.model({ content: a.string(), completed: a.boolean(), }) .authorization(allow => [allow.publicApiKey()]),});const client = generateClient<Schema>();
const todo = await client.models.Todo.create({ content: 'Buy Milk', completed: false });console.log(`New Todo created: ${todo.id}`); // New Todo created: 5DB6B4CC-CD41-49F5-9844-57C0AB506B69必要に応じて、Amplify Data を使用して単一フィールドと複合識別子を定義できます。
- コンシューマー提供値を持つ単一フィールド識別子(型:
idまたはstring、requiredでマークされている必要があります) - コンシューマー提供値のセットを持つ複合識別子(型:
idまたはstring、requiredでマークされている必要があります)
単一フィールド識別子
デフォルトの id 識別子フィールドをカスタマイズする必要がある場合、別のフィールドの名前を渡すことで実行できます。
const schema = a.schema({ Todo: a.model({ todoId: a.id().required(), content: a.string(), completed: a.boolean(), }) .identifier(['todoId']) .authorization(allow => [allow.publicApiKey()]),});const client = generateClient<Schema>();
const { data: todo, errors } = await client.models.Todo.create({ todoId: 'MyUniqueTodoId', content: 'Buy Milk', completed: false });console.log(`New Todo created: ${todo.todoId}`); // New Todo created: MyUniqueTodoId複合識別子
複数のフィールドによってアイテムが一意に識別される場合、フィールド名の配列を identifier() 関数に渡すことができます。
const schema = a.schema({ StoreBranch: a.model({ geoId: a.id().required(), name: a.string().required(), country: a.string(), state: a.string(), city: a.string(), zipCode: a.string(), streetAddress: a.string(), }).identifier(['geoId', 'name']) .authorization(allow => [allow.publicApiKey()]),});const client = generateClient<Schema>();
const branch = await client.models.StoreBranch.get({ geoId: '123', name: 'Downtown' }); // All identifier fields are required when retrieving an item