mickhansen / graphql-sequelize

GraphQL & Relay for MySQL & Postgres via Sequelize
MIT License
1.9k stars 172 forks source link

Question: How to make relations work? (Example project with sqlite DB inside) #629

Closed ArturBaybulatov closed 5 years ago

ArturBaybulatov commented 5 years ago

I got an example project, where I've set up a simple schema:

https://github.com/ArturBaybulatov/_nodejs-playground/tree/master/graphql-sequelize-basic-example (sample sqlite DB included; clone the repo, cd graphql-sequelize-basic-example, run npm install, then npm start to start the project)

So, when I query:

{
  categories(Id: 8) {
    Id
    CategoryName

    products {
      ProductName
      CategoryId
    }
  }
}

I expect to get only products from that category (with ID 8), but I get everything from a table:

image

Is there a way to fix this? Have I defined the schema the wrong way? Thanks

mickhansen commented 5 years ago

You've left out the most relevant piece of code, the schema implementation with resolvers.

ArturBaybulatov commented 5 years ago

Example code in the repository I provided, in the schema.js file. If I understood you right

Aukhan commented 5 years ago

https://github.com/ArturBaybulatov/_nodejs-playground/blob/c32bbf5fa8031b7194eb9ec6d041895b0d66b3a9/graphql-sequelize-basic-example/schema.js#L47

This line is incorrect it needs to be defined as an association rather than a direct model, that's why you are getting all Products

this will change to resolve: graphqlSequelize.resolver(models.Category.associations.Product),

mickhansen commented 5 years ago

@ArturBaybulatov Was looking for the code for the specific resolver. However @Aukhan provided the answer

Aukhan commented 5 years ago

@mickhansen I would like to play my part in keeping this repo moving, we are using this repo in two major products now, keeping all opinions aside, I feel like this and Sequelize are great libraries and must be kept alive. Please let me know if i could help out with triaging, setting up release goals and contribute code. There's a bunch of issues that can be closed, some need more information while a few are real. Thanks !

mickhansen commented 5 years ago

@Aukhan That sounds great, can always use help.

Aukhan commented 5 years ago

thanks @mickhansen, I guess this particular issue can be closed

ArturBaybulatov commented 5 years ago

@Aukhan Thanks for the response! It worked for me with the following line (with "Products", not "Product")

resolve: graphqlSequelize.resolver(models.Category.associations.Products),
Aukhan commented 5 years ago

@ArturBaybulatov correct, that's because it's a many relationship and sequelize pluralizes it but I hope you get the idea.