简体   繁体   中英

Resolver is the best practice for difficult query to Graphql?

I am learning about GraphQL with Laravel. When i need to response from difficult Query (include subquery or group by) I can do this with resolver.

For example.

select * from A where id in (select id from B where name='~~')

But i wonder this is the best way (best practice) to response. Can anyone give me answer?

My best practice is to think outside from the database tables point of view and focus the thinking on the domain model.

So the domain model object graph should have two types A and B and they should be somehow related to each other through a field.

Suppose A is a soccer team and B is a player. So basically , what you want to do in this SQL:

select * from A where id in (select a_id from B where name='~~')

is to find all soccer team information which contain some player whose name is called blablabla from the domain model point of view.

So maybe we can have two types called Team and Player :

type Team {
    id      : Int!
    name    : String
    address : String
    players : [Player]
}
type Player {
    id    : Int!    
    name  : String
    age   : Int
    team  : Team
}

To get all soccer teams data, we need to have a root query for it :

extend type Query {
   teams : [Team]
}

Since we need to filter the returned team based on some conditions , we can design an input object to represent such filter :

input TeamFilter {
  includePlayerName : String
}

and apply this filter to the teams query.It then becomes:

extend type Query {
   teams (filter: TeamFilter) : [Team]
}

Now , we can create a query to define what we want to retrieve. For example :

query {
    teams(filter : {
      includePlayerName : "*Peter*"  
    }){
       id 
       name
    }
}

is equivalent to the SQL:

  select id, name from Team where id in (select team_id from Player where name likes '%Perter%')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM