2

l am a rookie of graphql, and l never used rest or other language like this.

l can just get the fixed value with my level now.

l have a schema file like follow demo.schema

schema {
  query: Query
}

type Query {
  id(id: Int): sub
}

type sub{
    name: String
    age: Int
}

here is demo.php:

declare(strict_types=1);
require_once 'vendor/autoload.php';
$typedef = file_get_contents('demo.graphql');

$rootValue = include 'rootvalue.php';

use \GraphQL\GraphQL;
use \GraphQL\Utils\BuildSchema;


// build schema and get query string
$schema = BuildSchema::build($typedef);
$param = file_get_contents("php://input");
$param = json_decode($param, true);
$param = $param['query'];

// get result and print it
$r = GraphQL::executeQuery($schema, $param, $rootValue)->toArray();
print_r(json_encode($r));

here is rootvalue.php

interface Root
{
    public function reslove($root, $args, $context);
}


class age implements Root
{
    public function reslove($root, $args, $context)
    {
        return 30;
    }
}

class name implements Root
{
    public function reslove($root, $args, $context)
    {
        return 'Miami';
    }
}

return [
    'id'       =>  function($root, $args){
        return $root;
    },

    'age'       =>  function($root, $args, $context) {
        $new = new age();
        return $new->reslove($root, $args, $context);
    },

    'name'       =>  function($root, $args, $context) {
        $new = new name();
        return $new->reslove($root, $args, $context);
    },
];

now l a mysql db table named user, it has id, name, age fields

how can l get the result like user.id=1

now, l can just return value like '30', 'Miami'.

But now, l need to fetch data by database, So it will be a query like this from client browser

query{
    id(id: 0){
        name
        age
    }
}

l know l cat get arg's value of id in rootvalue.php

'id'=>function($root, $args){
        $args['id'] // it will be get a value '1'
        return $root;
    },

but it is my limit what l can do. l can't get id in other place, how to do this?

PS: l know how to get data from database, just don't know the time to fetch database, and how to transfer these data to sub object

afraid.jpg
  • 965
  • 2
  • 14
  • 31

0 Answers0