0

Normally I wouldn't try and create a relationship between primary keys within my Amplify Schema, though I am trying to recreate a friends code so that I can regularly deploy it with Amplify, hence I don't really have an option in this case.

My question is that I would like to create a link between these two Primary keys and was wondering if there is a way to do that, I have already followed the documentation here as well.

Ideally I would like to have my schema.graphql file look like this:

type ShoppingList @model @key(fields: ["UPC"]) {
    UPC: Products @connection
    quantity: Int
    timestamp: Int
}

type Products @model @key(fields: ["UPC"]) {
    UPC: String!
    Description: String
    Name: String
    Price: Float
    ProductId: String
    combinedSeaarchKey: String
    Img_URL: String
    LongDescription: String
    UserForRecommendations: Boolean
    Hidden: Boolean
    TrainingImageWidthInches: Float
}

When trying to deploy this, I get the error "Expected scalar and got Products".

Ideally I want to have the schema the same as well, since I don't want to go re-writing my friends client side application, and would rather try and fix it in the schema!

Hence any help would be greatly appreciated! Thanks

MHausner
  • 75
  • 1
  • 7

1 Answers1

2

Was looking for a solution to the same general issue, came across your post, but then solved my issue. My issue was a little unrelated, I was trying to sort on a non-scalar field. In your case, you're receiving that error by trying to make a key out of a non-scalar entity. Remove that @key from ShoppingList and you should clear your error, but let's talk through what I believe you're trying to achieve.

I assume you're trying to make a 1:Many relationship between ShoppingList and Products.

In your ShoppingList code, you have Products as a single entity but likely meant to have an array of Products:

UPC: [Products]

From there you need to define your connection between UPC and Products. You correctly called out the use of @connection, but didn't create the connection. To create the connection in a 1:Many relationship, you're going to want 1 ShoppingList and many Products. To achieve this, you likely want the following:

type ShoppingList @model {
    id: ID! #make sure you're specifying a PK for each object
    UPC: [Products] @connection(keyName: "relatedShoppingList" fields: ["id"])
    quantity: Int
    timestamp: Int
}

type Products @model {
    id: ID!
    parentShoppingList: ShoppingList @connection(fields: "relatedShoppingList")
    UPC: String!
    Description: String
    Name: String
    Price: Float
    ProductId: String
    combinedSearchKey: String
    Img_URL: String
    LongDescription: String
    UserForRecommendations: Boolean
    Hidden: Boolean
    TrainingImageWidthInches: Float
}

I foresee some additional issues with your data setup, but this should unblock your 1:many relationship between products and shopping lists.

mr_yager
  • 54
  • 6