Search code examples
javascriptgraphqlgraphcool

duplicated items with mutation graph cool / graphql


I am using graphcool / graphql and want to add Player to a Team. My schema looks like the following:

type Team @model {
  id: ID! @isUnique
  name: String
  players: [Player!]! @relation(name: "TeamPlayers")
  fixtures: [Fixture!]! @relation(name: "TeamFixtures")
  results: [Result!]! @relation(name: "TeamResults")
}

type Player @model {
    id: ID! @isUnique
    name: String!
    gamesPlayed: Int!
    goalsScored: Int!
    yellowCards: Int!
    redCards: Int!
    photo: String!
    team: Team! @relation(name: "TeamPlayers")
}

I am making the following mutations:

mutation {
      createPlayer(
      name: "Peter Flanagan",
      gamesPlayed: 1,
      yellowCards: 0,
      redCards: 1,
      goalsScored: 4,
      photo: "http://cdn2-www.craveonline.com/assets/uploads/2017/02/bret1.png",
      team: {
        name: "Man United"
      }
    ) {
        id
      }
}

This works as expected, but if I make another mutation, like the one below, a second team, also called Man United with a new id.

mutation {
      createPlayer(
      name: "Eric Cantona",
      gamesPlayed: 1,
      yellowCards: 0,
      redCards: 1,
      goalsScored: 4,
      photo: "http://cdn2-www.craveonline.com/assets/uploads/2017/02/bret1.png",
      team: {
        name: "Man United"
      }
    ) {
        id
      }
}

Can anyone advise how I can avoid this issue and add both Players to the same Team?


Solution

  • In this way, you always create new Team with creating new Player. If you want to connect player to team. Create team first and get teamId. With teamId then you can create mutation what connects to team like this:

    mutation {
      createPlayer(
      name: "Peter Flanagan",
      gamesPlayed: 1,
      yellowCards: 0,
      redCards: 1,
      goalsScored: 4,
      photo: "http://cdn2-www.craveonline.com/assets/uploads/2017/02/bret1.png",
      teamId: "TEAM_ID"
    ) {
        id
      }
    }