简体   繁体   中英

wpgraphql custom connection is returning null json

I was trying to fetch data from the wordpress custom tabel however the json in wpgraphql is return nothing

            `
{
                "data": {
                    "customers": {
                    "nodes": []
                    }
                },
                "extensions": {
                    "debug": [],
                    "tracing": {
                    "version": 1,
                    "startTime": 1674985374.163901,
                    "endTime": 1674985374.182393,
                    "duration": 18491,
                    "execution": {
                        "resolvers": [
                        {
                            "path": [
                            "customers"
                            ],
                            "parentType": "RootQuery",
                            "fieldName": "customers",
                            "returnType": "RootQueryToCustomerConnection",
                            "startOffset": 15638,
                            "duration": 1742
                        },
                        {
                            "path": [
                            "customers",
                            "nodes"
                            ],
                            "parentType": "RootQueryToCustomerConnection",
                            "fieldName": "nodes",
                            "returnType": "[Customer!]!",
                            "startOffset": 17647,
                            "duration": 7
                        }
                        ]
                    }
                    },
                    "queryLog": [
                    "Query Logging has been disabled. The 'SAVEQUERIES' Constant is set to 'false' on your server."
                    ],
                    "queryAnalyzer": {
                    "keys": "b8e3177963ec0ae1ea1edc35f5d818248bb0e460feecb0ac25cdaff638cd545e graphql:Query operation:NewQuery list:customer",
                    "keysLength": 111,
                    "keysCount": 4,
                    "skippedKeys": "",
                    "skippedKeysSize": 0,
                    "skippedKeysCount": 0,
                    "skippedTypes": []
                    }
                }
                }`


                My Code is this 

                `
                register_activation_hook( __FILE__, 'wpgraphql_customer_db_table');

                /**
                * When the plugin is activated, create the table
                * if it doesn't already exist
                */
                function wpgraphql_customer_db_table() {
                
                    global $table_prefix, $wpdb;
                
                    $table_name = 'customers';
                    $wp_table = $wpdb->prefix . $table_name;
                    $charset_collate = $wpdb->get_charset_collate();
                
                    /**
                    * If the table doesn't already exist
                    */
                    if ( $wpdb->get_var( "show tables like '$wp_table") != $wp_table ) {
                
                        require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );
                
                        $sql = "
                        CREATE TABLE $wp_table (
                            `id` int(11) NOT NULL AUTO_INCREMENT,
                            `first_name` varchar(100) NOT NULL,
                            `last_name` varchar(100) NOT NULL,
                            `email` varchar(100) NOT NULL,
                            `password` varchar(225) NOT NULL,
                            PRIMARY KEY (`id`)
                        ) $charset_collate;
                        ";
                
                        dbDelta( $sql );
                
                    }
                
                }

                /**
                * Hook into graphql init to extend GraphQL functionality
                */
                add_action( 'graphql_init', function() {

                    class CustomerConnectionResolver extends \WPGraphQL\Data\Connection\AbstractConnectionResolver {

                        public function get_loader_name() {
                            return 'customers';
                        }
                        
                        public function get_query_args() {
                            return [];
                        }

                        public function get_query() {
                            global $wpdb;
                            
                            $ids_array = $wpdb->get_results(
                                $wpdb->prepare(
                                    'SELECT id FROM `".$wpdb->prefix."customers` WHERE 1'
                                )
                            );
                            
                            $ids = ! empty( $ids_array ) ? array_values(array_column($ids_array, 'id')) : [];
                            return $ids;

                            // wp_send_json($ids);
                            // print_r($ids);
                            // die();
                        }

                        public function get_ids() {
                            return $this->get_query();
                        }

                        public function is_valid_offset( $offset ) {
                            return true;
                        }

                        // public function is_valid_model( $model ) {
                        //  return true;
                        // }

                        public function should_execute() {
                            return true;
                        }

                    }

                    /**
                    * Class NotificationsLoader
                    *
                    * This is a custom loader that extends the WPGraphQL Abstract Data Loader.
                    */
                    class CustomersLoader extends \WPGraphQL\Data\Loader\AbstractDataLoader {

                        public function loadKeys( array $keys ) {
                            if ( empty( $keys ) || ! is_array( $keys ) ) {
                                return [];
                            }

                            global $wpdb;
                            $results = $wpdb->get_results(
                                $wpdb->prepare(
                                    "SELECT * FROM `".$wpdb->prefix."customers` WHERE `id` in (".implode(',',$keys).")"
                                )
                            );

                            $results_by_id = [];
                            foreach ( $results as $result ) {

                                $customer = [
                                    // 'DatabaseId' => $result->id,
                                    'firstName' => $result->first_name,
                                    'lastName' => $result->last_name,
                                    // 'email' => $result->email,
                                    // 'password' => $result->password,
                                ];

                                $results_by_id[ (int) $result->id ] = $customer;
                            }
                            echo $results_by_id;
                            $customers = [];
                            foreach ( $keys as $key ) {
                                if ( isset( $results_by_id[ $key ] ) ) {
                                    $customers[$key] = $results_by_id[ $key ];
                                }
                            }
                            // graphql_debug($customers);
                            return $customers;
                        }

                    }
                    
                    add_filter( 'graphql_data_loaders', function( $loaders, $context ) {
                        $loaders['customers'] = new CustomersLoader( $context );
                        return $loaders;
                    }, 10, 2 );

                } );


                /**
                * Hook into GraphQL Schema initialization to register types
                * and fields to the Schema
                */
                add_action( 'graphql_register_types', function() {

                    # 1: Register the Type
                    register_graphql_object_type( 'Customer', [
                        'description' => __( 'Customer Records from Custom Table', 'wp-graphql-customers' ),
                        'fields' => [
                            // 'DatabaseId' => [
                            //  'type' => [ 'non_null' => 'Int' ],
                            //  'description' => __( 'Identifier of the customers database record id', 'wp-graphql-customers' ),
                            // ],
                            'firstName' => [
                                'type' => 'String',
                                'description' => __( 'First Name of the Customer', 'wp-graphql-customers' )
                            ],
                            'lastName' => [
                                'type' => 'String',
                                'description' => __( 'Last Name of the Customer', 'wp-graphql-customers' )
                            ],
                            // 'email' => [
                            //  'type' => 'String',
                            //  'description' => __( 'Email of the Customer', 'wp-graphql-customers' )
                            // ],
                            // 'password' => [
                            //  'type' => 'String',
                            //  'description' => __( 'Password  of customers', 'wp-graphql-customers' )
                            // ],

                        ],
                        'interfaces' => [ 'Node' ],
                        
                    ] );

                    # 2: Register the connection
                    register_graphql_connection( [
                        'fromType' => 'RootQuery',
                        'toType' => 'Customer' ,
                        'fromFieldName' => 'customers',
                        'resolve' => function( $source, $args, $context, $info ) {
                            $resolver = new CustomerConnectionResolver( $source, $args, $context, $info );
                            return $resolver->get_connection();
                        },
                        
                    ]);

                } );

What I am doing wrong please help.

I would like to return data something like

{
                "data": {
                    "posts": {
                    "edges": [
                        {
                        "node": {
                            "firstName": "shank",
                            "lastName": "Nath"
                        }
                        }
                    ]
                    }
                }

The SQL query to fetch data from the customers table is missing a quotation mark at the end:

$wpdb->get_var( "show tables like '$wp_table") != $wp_table

It should be:

$wpdb->get_var( "show tables like '$wp_table'") != $wp_table

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