Polymorphism

Hey,

Assuming this is my scheme:

interface IAnimal{
    id: ID!
    name: String!
}
type Cow implements IAnimal{
    color: String!
}
type Pig implements IAnimal{
    weight: Int!
}
type Horse implements IAnimal{
    nickname: String!
}
type Farm{
    animals: [IAnimals!]!
}

How can I assemble a query that will return for each animal the extra fields it has.
For example, if there are a horse and a pig in the Farm I want to get the id, name, and nickname for the horse and for the pig the id, name, and weight.

Thanks,
Or

Using DQL, you could use the expand predicate .
For example,

{
  getCow(func: type("Cow")) {
     expand(_all_)
  } 
}

would return all fields and their values for type Cow.

I will clearify my question
I want to get al the animals in the farm but for each animal present all of its data.
in the farm I have an array of IAnimals as I mentioned in the schema so the type should be figured on runtime.
That’s the kind of query I am looking for and it should be in GQL if possible.

In that case you can use the following,

query  { 
  queryFarm {
    animals {
        id
        name
        ... on Cow {  color  }
        ... on Pig {  weight  }
      }
  }
}
1 Like

Great thanks :slight_smile:

1 Like